radiance 1.7.0

- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves
  every shipped container
- Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime
- /v1/messages works with Claude Code as it ships (gearwave00001)
- a long agent conversation keeps its cached history when the client rewrites its last turn
  (manueloverride)
- a stream's first event goes out with the first token, so llama-benchy measures prefill right
- opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42)
- four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b)
- NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA
  adapters (baKon)
- many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool
  arguments and the CPU's vision and audio encoders
- plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-16 18:25:18 +02:00
1 parent b068190326
commit 1e968f6e1d
739 files changed
+128447 -84632

No files matched your search

+43 -52
View File
@@ -1,47 +1,37 @@
# tools/ -- rad-info, rad-convert, rad-kbench, rad-tune, and the smaller checkers below.
#
# The rad_add_tool tools link rad_core, and they do that rather than reimplementing anything
# because three of them ARE the engine's startup with a different last step: rad-convert,
# rad-kbench and rad-tune each load the same plugins in the same hierarchy and run the same
# declare phase (spec §4.2, §15, §17). A tool that resolved kernels differently from the engine
# would be a tool whose answers are about a different program.
# rad_add_tool tools link rad_core: rad-convert, rad-kbench and rad-tune are the engine's startup
# with a different last step, loading the same plugins in the same hierarchy and running the same
# declare phase (spec §4.4, §15, §17), so they resolve kernels exactly as the engine does.
#
# iface.cpp is the seam onto core/plugin and core/build; opshapes.cpp is the operand sizing
# rad-kbench and rad-tune share, and kfixture.cpp the recorded kernel fixture and its input draw.
# All three are compiled into each tool rather than made a library -- three files against four
# small binaries is not worth a target.
# iface.cpp is the seam onto core/plugin and core/build and the flag parsing every tool shares,
# opshapes.cpp the operand sizing shared by rad-kbench and rad-tune, kfixture.cpp the recorded
# kernel fixture and its input draw, and kbench_core.cpp rad-kbench's rules (comparison,
# tolerances, keys, the reference cache). They are compiled into each tool; a library target is not
# worth it for four files.
set(RAD_TOOL_SHARED
${CMAKE_CURRENT_SOURCE_DIR}/iface.cpp
${CMAKE_CURRENT_SOURCE_DIR}/opshapes.cpp
${CMAKE_CURRENT_SOURCE_DIR}/kfixture.cpp)
${CMAKE_CURRENT_SOURCE_DIR}/kfixture.cpp
${CMAKE_CURRENT_SOURCE_DIR}/kbench_core.cpp)
function(rad_add_tool name src)
add_executable(${name} ${src} ${RAD_TOOL_SHARED})
# WHOLE_ARCHIVE, for the same reason as ENABLE_EXPORTS below and it is the other half of it.
# A static archive yields only the objects that resolve a symbol the executable itself
# references, and rad-convert never calls rad_issue -- so without it core/runtime/issue.cpp is
# dropped from the link and the architecture plugin, which DOES call it from its step function,
# fails to load with "undefined symbol: rad_issue". A host that dlopens a plugin has to present
# the WHOLE plugin-facing ABI, declare phase and run phase alike, whether or not it uses all of
# it.
# WHOLE_ARCHIVE: a host that dlopens a plugin must present the whole plugin-facing ABI, declare
# and run phase alike. A plain archive link drops objects the tool does not reference (e.g.
# rad-convert never calls rad_issue), and the architecture plugin then fails to load.
target_link_libraries(${name} PRIVATE "$<LINK_LIBRARY:WHOLE_ARCHIVE,rad_core>")
target_include_directories(${name} PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/core
${CMAKE_SOURCE_DIR}/abi)
# NO HOME DEFINITION HERE. rad_abi carries RAD_DEFAULT_HOME to everything that links it, the
# engine and the tools alike, and iface.cpp's rad_home() reads that macro, so there is ONE
# definition of the default home. A second one derived from the install prefix would put the
# tools one directory away from core/config.cpp's default, and nothing would show it until an
# install: "no plugins" reads the same whichever wrong directory it came from.
# No home definition here: rad_abi carries RAD_DEFAULT_HOME to the engine and tools alike, and
# iface.cpp's rad_home() reads it, so there is one default home.
#
# ENABLE_EXPORTS, and it is load-bearing rather than tidy. The declare-phase C ABI
# (rad_decl_weight, rad_decl_op, rad_declare_logits, ...) is implemented by the HOST and an
# architecture plugin binds to it at dlopen. Without --export-dynamic those symbols are not in
# the executable's dynamic table and EVERY architecture plugin fails to load with "undefined
# symbol: rad_decl_weight". Kernel plugins do not need it -- they only export -- which is why
# rad-schemas and r4d_selftest work without it.
# ENABLE_EXPORTS is required: the host implements the declare-phase C ABI (rad_decl_weight,
# rad_decl_op, rad_declare_logits, ...) and an architecture plugin binds to it at dlopen. Kernel
# plugins only export, so rad-schemas and r4d_selftest do not need it.
set_target_properties(${name} PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
ENABLE_EXPORTS ON)
@@ -49,57 +39,58 @@ endfunction()
rad_add_tool(rad-info rad_info.cpp)
# The tokeniser's reference encoder: an independent encode path (tokref.h) that core/text's
# pre-tokeniser compiler is held to. A library rather than a tool source because
# tests/tokenizer_test compares against it too; nothing in core/ links it.
# The tokeniser's independent reference encoder (tokref.h), which core/text's pre-tokeniser is
# checked against. A library because tests/tokenizer_test uses it too; core/ does not link it.
add_library(rad_tokref STATIC ${CMAKE_CURRENT_SOURCE_DIR}/tokref.cpp)
target_link_libraries(rad_tokref PUBLIC rad_core)
target_include_directories(rad_tokref PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/core)
# rad-tokcheck needs neither plugins nor the declare phase, so it links the core plainly rather
# than through rad_add_tool's whole-archive link.
add_executable(rad-tokcheck rad_tokcheck.cpp)
# rad-tokcheck needs neither plugins nor the declare phase, so it links the core plainly.
add_executable(rad-tokcheck rad_tokcheck.cpp ${CMAKE_CURRENT_SOURCE_DIR}/iface.cpp)
target_link_libraries(rad-tokcheck PRIVATE rad_tokref rad_core)
set_target_properties(rad-tokcheck PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
# Not a rad_add_tool: it links no core at all, deliberately. It dlopens plugins and reads their
# static schema tables, so it works on a plugin the engine cannot even load -- which is exactly
# when you need it.
# rad-schemas links no core: it dlopens plugins and reads their static schema tables, so it works on
# a plugin the engine cannot load.
add_executable(rad-schemas rad_schemas.cpp)
target_link_libraries(rad-schemas PRIVATE rad_abi ${CMAKE_DL_LIBS})
set_target_properties(rad-schemas PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
rad_add_tool(rad-convert rad_convert.cpp)
# OpenMP across weights, and within a large one. Without it the same code runs one thread.
# Optional OpenMP across weights and within a large one.
find_package(OpenMP QUIET)
if(OpenMP_CXX_FOUND)
target_link_libraries(rad-convert PRIVATE OpenMP::OpenMP_CXX)
else()
message(STATUS "rad-convert: no OpenMP -- conversion will run single-threaded")
endif()
rad_add_tool(rad-kbench rad_kbench.cpp)
# The timing pass (--bench): the only part of rad-kbench that needs the device layer's internals.
target_sources(rad-kbench PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/kbench_timer.cpp)
rad_add_tool(rad-tune rad_tune.cpp)
# The GBNF mask engine's acceptance run: the differential and latency suite of tests/gbnf_test.cpp
# against a real tokenizer.json and chat template, given by path. Not a rad_add_tool -- it loads no
# plugin and declares nothing -- and not installed: it compiles in upstream's candidate walk as its
# oracle, which is test code (tests/gbnf_oracle.cpp) and belongs in no shipped binary.
add_executable(rad-gbnf-check rad_gbnf_check.cpp ${CMAKE_SOURCE_DIR}/tests/gbnf_oracle.cpp)
# GBNF mask engine acceptance run: tests/gbnf_test.cpp's differential and latency suite against a
# real tokenizer.json and chat template. It loads no plugin, and is not installed because it
# compiles in test code (tests/gbnf_oracle.cpp, upstream's candidate walk) as its oracle.
add_executable(rad-gbnf-check rad_gbnf_check.cpp ${CMAKE_SOURCE_DIR}/tests/gbnf_oracle.cpp
${CMAKE_CURRENT_SOURCE_DIR}/iface.cpp)
target_link_libraries(rad-gbnf-check PRIVATE rad_core)
target_include_directories(rad-gbnf-check PRIVATE
${CMAKE_SOURCE_DIR}/core ${CMAKE_SOURCE_DIR}/abi ${CMAKE_SOURCE_DIR}/tests)
${CMAKE_SOURCE_DIR}/core ${CMAKE_SOURCE_DIR}/abi ${CMAKE_SOURCE_DIR}/tests
${CMAKE_CURRENT_SOURCE_DIR})
set_target_properties(rad-gbnf-check PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
# rad-schemas is the tool an installed prefix needs most: it links no core, so it reads a plugin's
# static schema tables on a plugin the engine cannot even load -- which is exactly the position
# somebody debugging their own out-of-tree plugin is in. The four exports it needs are the four
# every kernel plugin has, so it answers before anything else in the stack will.
# rad-schemas matters most in an installed prefix: it needs only the four exports every kernel
# plugin has, so it can debug an out-of-tree plugin the engine cannot load.
install(TARGETS rad-info rad-convert rad-kbench rad-tune rad-schemas rad-tokcheck
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
# rad-chatparse: the reply parser's acceptance run against a checkpoint's real tokenizer and chat
# template, beside the legacy parser in tests/legacy/. It shares the differential harness and that
# parser with tests/chatparse_test, so it exists only in a build that has the tests.
# 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)
add_executable(rad-chatparse rad_chatparse.cpp ${CMAKE_CURRENT_SOURCE_DIR}/iface.cpp)
target_link_libraries(rad-chatparse PRIVATE rad_legacy_toolparse)
target_include_directories(rad-chatparse PRIVATE ${CMAKE_SOURCE_DIR}/core ${CMAKE_SOURCE_DIR}/abi)
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)
endif()
+21 -30
View File
@@ -1,28 +1,23 @@
/* dashcheck -- run the dashboard's own script against real /stats payloads and report what a
* reader would call a bug: NaN, undefined, Infinity, or a throw.
/* dashcheck -- run the dashboard's own script against a sequence of real /stats payloads and
* report NaN, undefined, Infinity, a throw, or a badly formatted figure.
*
* WHY THIS AND NOT A BROWSER. The dashboard is one self-contained page driven by one endpoint, so
* the interesting failures are arithmetic rather than layout -- a rate differenced over a zero
* interval, a panel whose model has no expert plane, a counter that went backwards. Those need the
* real payloads, which a browser adds nothing to, and they need a SEQUENCE of them, which is
* awkward to arrange in one.
* The dashboard is one page driven by one endpoint, so its failures are arithmetic, not layout (a
* rate differenced over a zero interval, a model with no expert plane, a counter that went
* backwards). Those need real payloads in sequence, which no browser adds anything to.
*
* AND poll() SWALLOWS EVERYTHING update() THROWS, marking the dot stale and nothing else. That is
* the right behaviour for a server that stopped answering and the wrong one for a page that
* cannot render what it was sent: the two look identical from outside. So this intercepts the
* exception where it is caught, and reads the dot afterwards -- "dot stale" means it threw.
* poll() catches whatever update() throws and only marks the dot stale, so a page that cannot
* render looks like a server that stopped answering. The exception is intercepted where it is
* caught, and "dot stale" afterwards means update() threw.
*
* AND A FIGURE CAN BE WRONG WITHOUT BEING NaN. The page formats every number through one block of
* functions (three significant figures rounded before the unit is chosen, binary sizes, decimal
* rates, SI prefixes, shares that never round onto 0% or 100%), so those functions are run against
* a table of boundary cases first, and every text the polls write is then searched for the shapes
* that rule exists to prevent: a raw float, a four-digit figure in front of a unit or a prefix the
* next rung replaces, a locale's thousands separator.
* The page formats every number through one block of functions (three significant figures rounded
* before the unit is chosen, binary sizes, decimal rates, SI prefixes, shares that never round onto
* 0% or 100%). Those run against a table of boundary cases first; then every text the polls write
* is searched for a raw float, four digits in front of a unit or prefix, or a thousands separator.
*
* node tools/dashcheck.js <saved dashboard html> <json array of /stats payloads>
*
* Take the payloads UNDER LOAD. Idle ones exercise none of the differencing, and every rate on the
* page is a difference.
* Capture the payloads under load: every rate on the page is a difference, which idle payloads do
* not exercise.
*/
const fs = require('fs');
const html = fs.readFileSync(process.argv[2], 'utf8');
@@ -61,9 +56,8 @@ const mkEl = (id) => {
clientWidth: 800, clientHeight: 400,
};
el.parentElement = el.parentNode;
/* A REAL ELEMENT HAS A TEXT NODE IN IT, and the page writes through it: setMetric sets
* firstChild.nodeValue rather than textContent. A stub without one throws inside the page's
* own try/catch and reads exactly like the bug it is meant to find. */
/* setMetric writes firstChild.nodeValue, not textContent, so every stub needs a text node; a
* stub without one throws inside the page's own try/catch and looks like a real bug. */
const tn = { nodeType: 3, _v: '' };
Object.defineProperty(tn, 'nodeValue', {
get(){ return tn._v; },
@@ -118,8 +112,7 @@ global.fetch = async (u) => ({
});
let threw = null;
/* poll() swallows whatever update() throws and only marks the dot stale, so the exception
* has to be intercepted where it is caught or it is gone. */
/* Record what update() throws at the one place poll() catches it. */
js = js.replace('$("dot").className = "dot stale";',
'globalThis.__err = globalThis.__err || e; $("dot").className = "dot stale";');
js += "\n;globalThis.__poll = typeof poll === 'function' ? poll : null;";
@@ -127,8 +120,8 @@ js += "\n;globalThis.__fmt = typeof ladder === 'function' ? { hb, hbOf, rate, cn
"pct, pctn, dur, stepTime } : null;";
try { (0, eval)(js); } catch (e) { threw = e; }
/* THE BOUNDARIES, where a formatter that picks its unit before rounding prints a figure in the
* unit the next one up exists to replace. Each value sits on or just either side of one. */
/* Unit boundaries, where a formatter that picks its unit before rounding prints a figure the
* next unit up should replace. Each value sits on or just either side of one. */
const G = 2 ** 30, T = 2 ** 40, NB = '\u202f';
const CASES = [
['hb', [0], '0 B'], ['hb', [999], '999 B'], ['hb', [1023], '1.00 KiB'], ['hb', [1536], '1.50 KiB'],
@@ -167,14 +160,12 @@ if (!globalThis.__fmt) {
}
(async () => {
/* show() hid the dashboard view during startup; poll() returns early when it is hidden,
* so without this the harness measures nothing and says everything is fine. */
/* show() hid the dashboard view during startup, and poll() returns early while it is hidden. */
get('view-dash').hidden = false;
for (let i = 0; i < payloads.length + 1; i++) {
try { if (globalThis.__poll) await globalThis.__poll(); } catch (e) { threw = threw || e; }
}
/* poll() catches everything update() throws and only marks the dot stale, so a real UI
* failure is invisible from outside. Read the dot: "dot stale" means it threw. */
/* "dot stale" means update() threw (see the header). */
const dot = els.has('dot') ? els.get('dot').className : '(never set)';
console.log(' dot after last poll: ' + dot);
if (/stale/.test(dot)) console.log(' UPDATE THREW (dashboard would read as stale, not broken)');
+19 -22
View File
@@ -1,25 +1,23 @@
/* gen_tokenizer_ucd -- writes core/text/tokenizer_ucd.cpp, the Unicode tables the pre-tokeniser
* regex compiler reads.
*
* The tables are READ OUT OF ONIGURUMA rather than derived from the UCD text files, because the
* reference a tokenizer.json pattern is judged against is HuggingFace `tokenizers`, and that
* library runs every Split pattern through Oniguruma. Whatever Oniguruma answers for `\p{L}`,
* `\s`, `\w` or `(?i:s)` is by definition what the pattern means, including where its Unicode
* version or its definition of a property differs from another engine's. So each table is the
* literal answer of `onig_match` for that property, codepoint by codepoint, and the case-folding
* orbits are Oniguruma's own case-fold enumeration.
* The tables are read out of Oniguruma rather than derived from the UCD files: HuggingFace
* `tokenizers` runs every Split pattern through Oniguruma, so its answer for `\p{L}`, `\s`, `\w`
* or `(?i:s)` defines what a pattern means, Unicode version and property quirks included. Each
* table is `onig_match` per codepoint; the case-folding orbits are Oniguruma's own enumeration.
*
* Not built by CMake, because it links the system Oniguruma and nothing else in the tree does:
* Not built by CMake, since nothing else links the system Oniguruma:
*
* g++ -O2 -std=c++20 tools/gen_tokenizer_ucd.cpp -lonig -o gen_tokenizer_ucd
* ./gen_tokenizer_ucd > core/text/tokenizer_ucd.cpp
*
* The Oniguruma it ran against is recorded in the output. Regenerate when the reference moves to a
* later Unicode version; tokenizer_regex_test's property and (?i) cases and tokenizer_test's
* Unicode-version case say what changed.
* The output records the Oniguruma version. Regenerate when the reference moves to a later
* Unicode version; tokenizer_regex_test's property and (?i) cases and tokenizer_test's
* Unicode-version case show what changed.
*/
#include <oniguruma.h>
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
@@ -153,11 +151,10 @@ int main() {
}
std::printf("\n};\nconst size_t k_gc_runs_n = sizeof(k_gc_runs) / sizeof(k_gc_runs[0]);\n\n");
/* `\w` has two definitions in Oniguruma. As an atom (and for `\b`) it asks the codepoint's
* ctype, which below U+0100 reads a Latin-1 table that counts the superscript digits and the
* vulgar fractions as word characters; inside a bracket class it adds the Unicode Word range
* table, which does not. Both are carried. The other shorthands agree in and out of a class,
* and the generator checks that rather than assuming it. */
/* `\w` has two definitions in Oniguruma. As an atom (and for `\b`) it uses the codepoint's
* ctype, whose Latin-1 table below U+0100 counts superscript digits and vulgar fractions as
* word characters; inside a bracket class it uses the Unicode Word ranges, which do not. Both
* are emitted. The other shorthands must agree in and out of a class, which is checked. */
for (const char* e : { "\\s", "\\d", "\\h" }) {
if (ranges_of(e) != ranges_of(std::string("[") + e + "]")) {
std::fprintf(stderr, "%s differs inside a class; the compiler assumes it does not\n", e);
@@ -169,8 +166,8 @@ int main() {
emit_ranges("k_word", ranges_of("\\w"));
emit_ranges("k_word_class", ranges_of("[\\w]"));
/* Scripts a pre-tokeniser is known to name, plus the neighbours a model for the same
* languages would. Anything else is refused by name at load. */
/* Scripts known pre-tokenisers name, plus likely neighbours. Others are refused by name at
* load. */
static const char* kScripts[] = {
"Han", "Hiragana", "Katakana", "Hangul", "Bopomofo", "Latin", "Greek", "Cyrillic",
"Armenian", "Hebrew", "Arabic", "Thai", "Lao", "Khmer", "Myanmar", "Tibetan",
@@ -189,10 +186,10 @@ int main() {
script_tables[i].c_str());
std::printf("};\nconst size_t k_scripts_n = sizeof(k_scripts) / sizeof(k_scripts[0]);\n\n");
/* Case folding, as Oniguruma enumerates it for a single codepoint under the default fold
* flags: every other codepoint the pattern character matches under (?i), and whether it also
* matches a MULTI-codepoint sequence (U+00DF against "ss"). The single-codepoint relation is
* closed into orbits; the multi-codepoint ones are listed so the compiler can refuse them. */
/* Case folding per codepoint under the default fold flags: the codepoints it matches under
* (?i), and whether it also matches a multi-codepoint sequence (U+00DF against "ss"). The
* single-codepoint relation is closed into orbits; multi-codepoint folds are listed so the
* compiler can refuse them. */
std::vector<uint32_t> parent(kMax);
std::iota(parent.begin(), parent.end(), 0u);
auto find = [&](uint32_t x) {
+36 -28
View File
@@ -1,25 +1,20 @@
/* iface.cpp -- the CLI plumbing every tool agrees about. Each tool parses its own flags: five
* hand-rolled loops is less machinery than one options library, and each usage text is then
* written for its own tool.
/* iface.cpp -- CLI plumbing shared by the tools.
*
* The plugin loader and the declare phase are not here: they live in core/build/startup.h, because
* they ARE the engine's startup -- rad-convert, rad-kbench and rad-tune are that startup with a
* different last step. One copy only; two would eventually disagree about hierarchy order, which
* is what decides the layout baked into a container.
* The plugin loader and declare phase stay in core/build/startup.h, shared with the engine: a
* second copy could disagree on hierarchy order, which decides the layout baked into a container.
*/
#include "iface.h"
#include "util/kernel_list.h"
#include <cerrno>
#include <cstdio>
#include <cstdlib>
namespace rad {
/* THE SAME DEFAULT THE ENGINE USES, spelled with the same macro.
*
* RAD_DEFAULT_HOME is the one definition of the fallback home, shared with core/config.cpp. It
* must not be respelled here in terms of the install prefix: the engine's home is a directory
* below that prefix, so a second spelling puts the tools and the engine one directory apart and
* they find different plugin trees. The divergence is invisible while every run passes --home or
* $RADIANCE_HOME explicitly, and appears the moment an installed prefix becomes a working home. */
/* Same fallback as the engine (core/config.cpp): RAD_DEFAULT_HOME. Do not derive it from the
* install prefix; the home is a directory below it, so the tools would find a different plugin
* tree. */
std::string rad_home() {
if (const char* e = std::getenv("RADIANCE_HOME")) if (*e) return e;
#ifdef RAD_DEFAULT_HOME
@@ -29,26 +24,39 @@ std::string rad_home() {
#endif
}
std::vector<std::string> rad_split_list(const std::string& s) {
std::vector<std::string> out;
std::string cur;
for (char c : s) {
if (c == ':' || c == ',') { if (!cur.empty()) out.push_back(cur); cur.clear(); }
else cur.push_back(c);
}
if (!cur.empty()) out.push_back(cur);
return out;
}
std::vector<std::string> rad_split_list(const std::string& s) { return rad_split_kernel_list(s); }
std::vector<std::string> rad_hierarchy_from_env() {
const char* e = std::getenv("RADIANCE_KERNELS");
return (e && *e) ? rad_split_list(e) : std::vector<std::string>{};
}
std::string rad_humanb_w(int64_t bytes, int w) {
std::string s = humanb(bytes);
if ((int)s.size() >= w) return s;
return std::string((size_t)(w - s.size()), ' ') + s;
bool rad_parse_int(const char* text, int64_t lo, int64_t hi, int64_t* out, std::string* why) {
char* end = nullptr;
errno = 0;
const long long n = text ? std::strtoll(text, &end, 10) : 0;
if (!text || !*text || !end || *end || errno == ERANGE) {
if (why) *why = fmt("takes a whole number, not '%s'", text ? text : "");
return false;
}
if (n < lo || n > hi) {
if (why) *why = hi == INT64_MAX ? fmt("must be >= %lld, not %lld", (long long)lo, n)
: fmt("must be in [%lld, %lld], not %lld", (long long)lo,
(long long)hi, n);
return false;
}
*out = n;
return true;
}
int64_t rad_flag_int(const char* tool, const char* flag, const char* text, int64_t lo, int64_t hi) {
int64_t v = 0;
std::string why;
if (!rad_parse_int(text, lo, hi, &v, &why)) {
std::fprintf(stderr, "%s: %s %s\n", tool, flag, why.c_str());
std::exit(2);
}
return v;
}
} /* namespace rad */
+22 -22
View File
@@ -1,14 +1,12 @@
/* iface.h -- what the tools need from components outside tools/.
*
* rad-info, rad-convert, rad-kbench and rad-tune sit on top of three things the
* format component does not own: the GGUF reader and the tokenizer.json parser (core/text), and
* the plugin registry and the declare phase (core/plugin, core/build). This header is the one
* place those expectations are written down, so they are one file to check rather than one per
* tool to grep, and so the tools have a single seam if any of them moves.
* rad-info, rad-convert, rad-kbench and rad-tune build on the GGUF reader and tokenizer.json parser
* (core/text) and the plugin registry and declare phase (core/plugin, core/build). This header is
* the tools' single seam onto them.
*
* rad-convert, rad-kbench and rad-tune all need exactly the same thing -- the plugins loaded in
* hierarchy order and the declare phase run against a model's metadata -- because all three are
* the engine's startup with a different last step (spec §4.2, §15, §17).
* rad-convert, rad-kbench and rad-tune are the engine's startup with a different last step: plugins
* loaded in hierarchy order and the declare phase run against a model's metadata (spec §4.4, §15,
* §17).
*/
#pragma once
#include "rad_core.h"
@@ -22,24 +20,26 @@
namespace rad {
/* The vocab pipeline lives in core/text: VocabBuild, parse_tokenizer_json, vocab_from_gguf and
* vocab_serialize. A tool that needs it includes text/tokenizer.h directly -- there is nothing to
* restate here, and restating it is how two definitions of VocabBuild come to exist. The
* container's half of that contract is RadWriter::intern_string() and set_vocab_section(). */
/* Plugin loading and the declare phase are core/build/startup.h -- they are the engine's startup,
* and rad-convert, rad-kbench and rad-tune are that startup with a different last step. */
/* The vocab pipeline (VocabBuild, parse_tokenizer_json, vocab_from_gguf, vocab_serialize) is in
* text/tokenizer.h; the container side is RadWriter::intern_string() and set_vocab_section().
* Plugin loading and the declare phase are in build/startup.h. */
/* ================================================================== shared CLI plumbing */
/* Every tool parses its own flags -- five hand-rolled loops is less machinery than one options
* library, and each usage text is then written for its own tool. What IS shared is the small set
* of things they must agree about. */
/* Each tool parses its own flags; these are the few things they must agree on. */
std::string rad_home(); /* $RADIANCE_HOME, else the install prefix */
std::vector<std::string> rad_hierarchy_from_env(); /* $RADIANCE_KERNELS, colon separated */
std::vector<std::string> rad_split_list(const std::string& s); /* ':' or ',' separated */
std::vector<std::string> rad_hierarchy_from_env(); /* $RADIANCE_KERNELS */
/* A kernel list as --kernels and $RADIANCE_KERNELS spell it: ',' or ':' separated, the same rule
* the engine reads them by (util/kernel_list.h). */
std::vector<std::string> rad_split_list(const std::string& s);
/* Bytes in human units, right-aligned in `w` columns. Every report that prints a size uses it. */
std::string rad_humanb_w(int64_t bytes, int w);
/* `text` as a whole decimal number in [lo, hi]: the engine's rule for a numeric flag
* (core/config.cpp), so "12k", "8x", "", "auto" and an overflow are refused rather than read as
* their leading digits or as 0. False with the reason in *why. */
bool rad_parse_int(const char* text, int64_t lo, int64_t hi, int64_t* out, std::string* why);
/* rad_parse_int for a flag's value: the number, or a message naming `tool` and `flag` on stderr
* and exit status 2. */
int64_t rad_flag_int(const char* tool, const char* flag, const char* text, int64_t lo, int64_t hi);
} /* namespace rad */
+30 -26
View File
@@ -1,19 +1,13 @@
#!/bin/sh
# kbench-analysis.sh -- the half of a kernel library's health that is not a number rad-kbench can
# measure: what a static analyser says about the source, and what a sanitised build says about the
# run.
# kbench-analysis.sh -- what a static analyser says about the kernel sources and a sanitised build
# says about a replay, as one markdown fragment that rad-kbench splices into its report with
# --analysis. Separate from rad-kbench because it runs in CI on machines without a GPU, while
# rad-kbench runs on a card.
#
# It writes ONE markdown fragment, which rad-kbench splices into its report with --analysis. That
# is deliberate rather than having the tool shell out: the tool is what somebody runs on a card,
# this is what somebody runs in CI on a machine that may have no GPU at all, and a report that
# needs both present to render is a report that renders nowhere.
# Usage: [JOBS=N] tools/kbench-analysis.sh <build-dir> <out.md> (JOBS defaults to every core)
#
# Usage: tools/kbench-analysis.sh <build-dir> <out.md>
#
# What it does NOT do is fail the build. Every finding here is advisory -- clang-tidy on a HIP
# translation unit reports things that are true of the language and not of the code, and a
# sanitised replay is a different binary from the one that ships. The numbers belong in the report
# so somebody reads them; gating on them would mean somebody turns the gate off.
# Advisory: it never fails the build. clang-tidy reports language-level noise on this code, and a
# sanitised replay is a different binary from the one that ships.
set -eu
BUILD=${1:-build}
@@ -32,10 +26,10 @@ TIDY=$(command -v clang-tidy || echo /opt/rocm/llvm/bin/clang-tidy)
} > "$OUT"
# ---------------------------------------------------------------- clang-tidy
# Only the checks that mean something for this code. `bugprone-*` and `clang-analyzer-*` are the
# ones that find real defects; the readability and naming packs would bury those under thousands
# of style opinions this tree has already decided against.
CHECKS='-*,bugprone-*,clang-analyzer-*,performance-*,-bugprone-easily-swappable-parameters,-bugprone-narrowing-conversions'
# The defect-finding packs only; the readability and naming packs would bury them under style
# findings this tree has decided against. performance-enum-size is excluded too: the ABI's enums
# are int-sized on purpose.
CHECKS='-*,bugprone-*,clang-analyzer-*,performance-*,-bugprone-easily-swappable-parameters,-bugprone-narrowing-conversions,-performance-enum-size'
if [ ! -f "$CC_JSON" ]; then
echo "clang-tidy: skipped, no $CC_JSON (configure with -DCMAKE_EXPORT_COMPILE_COMMANDS=ON)" >> "$OUT"
@@ -46,10 +40,16 @@ elif [ ! -x "$TIDY" ] && ! command -v clang-tidy > /dev/null 2>&1; then
else
TMP=$(mktemp)
# Host C++ only. A HIP translation unit needs the offload flags clang-tidy will not replay, and
# it reports the __device__ attributes as errors rather than analysing the code.
for f in $(find "$ROOT/libref" "$ROOT/core" "$ROOT/tools" -name '*.cpp' | sort); do
"$TIDY" -p "$BUILD" --checks="$CHECKS" --quiet "$f" 2>/dev/null || true
done > "$TMP"
# it reports the __device__ attributes as errors rather than analysing the code. One process per
# unit, each into its own file, and a warning in a header counts once however many units
# include it.
PARTS=$(mktemp -d)
find "$ROOT/libref" "$ROOT/core" "$ROOT/tools" -name '*.cpp' | sort |
xargs -P "${JOBS:-$(nproc)}" -I{} sh -c \
'"$1" -p "$2" --checks="$3" --quiet "$4" > "$5/$(echo "$4" | tr / _).log" 2>/dev/null || true' \
sh "$TIDY" "$BUILD" "$CHECKS" {} "$PARTS"
cat "$PARTS"/*.log | grep "warning:" | sort -u > "$TMP"
rm -rf "$PARTS"
N=$(grep -c "warning:" "$TMP" || true)
echo "### clang-tidy" >> "$OUT"
@@ -58,7 +58,7 @@ else
echo "(\`libref/\`, \`core/\`, \`tools/\`). HIP units are excluded: clang-tidy cannot replay the" >> "$OUT"
echo "offload flags and reports \`__device__\` as an error rather than analysing the body." >> "$OUT"
echo >> "$OUT"
echo "- $N warning(s)" >> "$OUT"
echo "- $N distinct warning(s)" >> "$OUT"
if [ "$N" -gt 0 ]; then
echo >> "$OUT"
echo "| check | count |" >> "$OUT"
@@ -71,18 +71,22 @@ else
fi
# ---------------------------------------------------------------- sanitised replay
# A second build tree, because -fsanitize changes every object and mixing them is how you get a
# link that succeeds and a binary that reports nothing.
# A second build tree: -fsanitize changes every object, and mixing sanitised and plain objects can
# link into a binary that reports nothing.
echo "### AddressSanitizer + UndefinedBehaviorSanitizer" >> "$OUT"
echo >> "$OUT"
SAN="$BUILD-asan"
if [ -x "$SAN/bin/rad-kbench" ]; then
LOG=$(mktemp)
# Both fixtures, one run per distinct case, and the reference always run: a cached answer
# would leave libref's code unexecuted under the sanitiser.
ASAN_OPTIONS=detect_leaks=0:abort_on_error=0 \
UBSAN_OPTIONS=print_stacktrace=1 \
"$SAN/bin/rad-kbench" --home "$SAN/radiance_home" > "$LOG" 2>&1 || true
"$SAN/bin/rad-kbench" --home "$SAN/radiance_home" --max-cases 1 --no-cache \
--fixture "$SAN/radiance_home/kernels.rkb" \
--fixture "$SAN/radiance_home/kernels_moe.rkb" > "$LOG" 2>&1 || true
E=$(grep -c "ERROR: AddressSanitizer\|runtime error:" "$LOG" || true)
echo "A sanitised replay of the whole fixture. Host code only -- see the note in the" >> "$OUT"
echo "A sanitised replay of both fixtures. Host code only -- see the note in the" >> "$OUT"
echo "**Memory safety** section for why the device side cannot be sanitised on this card." >> "$OUT"
echo >> "$OUT"
echo "- $E report(s)" >> "$OUT"
File diff suppressed because it is too large. Load diff
+465
View File
@@ -0,0 +1,465 @@
/* kbench_core.h -- rad-kbench's rules, apart from its plumbing.
*
* Everything here is a pure function of its arguments or a small file format: how two outputs are
* compared, which tolerance an op gets, what a cap or cache key is made of, what the exit code is,
* how much memory a case may take, and how a reference answer is cached. rad_kbench.cpp wires these
* to plugins, devices and the fixture; tests/kbench_test.cpp checks the rules directly, and
* tests/kbench_mutant_test.cpp checks the wiring with known-bad kernels.
*/
#pragma once
#include "kfixture.h"
#include "opshapes.h"
#include <chrono>
#include <cstdint>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
namespace rad {
namespace kb {
/* ================================================================== elementwise comparison */
struct Err {
double max_abs = 0;
double max_rel = 0;
double rel_l2 = 0;
int64_t n_nonfinite_mismatch = 0; /* elements finite on one side and not the other */
int64_t n = 0;
};
/* rel_l2 over the finite elements both sides agree are finite. A zero reference against a
* non-zero output is 1, against a zero output 0. */
Err compare(const float* got, const float* ref, int64_t n);
/* Whether an operand's error replaces the worst so far when reporting a case: a failing operand
* before a passing one, then the larger error. A NaN, once worst, stays worst. Start from
* worst_rel < 0 so the first operand always takes it. */
bool takes_worst(double rel, bool bad, double worst_rel, bool worst_bad);
/* The larger of two errors, where NaN is the largest. std::max(a, NaN) returns a, which would
* report a NaN case's worst error as whatever came before it. Negative means "none yet". */
double worst_of(double a, double b);
/* ================================================================== tolerances */
/* Keyed by (op prefix, activation dtype), most specific first, "*" matching anything. Each value
* covers what a different summation order of the same arithmetic costs, with a margin, and stays
* far below what a wrong kernel costs. The activation dtype is `dtype`, else attention's
* `q_dtype`, else `kv_dtype`. */
struct TolRow { const char* op; const char* dtype; double rel_l2; };
struct TolPick {
double rel_l2 = 0;
const TolRow* row = nullptr; /* the table row it came from; null for an override */
bool catch_all = false; /* the ("*", "*") row: no row was chosen for this op */
};
/* The activation dtype an op's parameters name, or null. */
const char* activation_dtype(const Geometry& g);
/* The tolerance for output `operand` of `op` at `g`. Per-operand overrides come first. */
TolPick tolerance_for(const std::string& op, const Geometry& g, const char* operand);
/* The rows themselves, for a test that walks every op of a fixture through them. */
const std::vector<TolRow>& tolerance_table();
/* ================================================================== index outputs
*
* A token id, an expert id or a top-k index is right or wrong, so it is compared exactly. A rel_l2
* over ids would pass an expert id off by one at M = 1 (rms ~150 over 8 ids gives 2.4e-3).
*
* The exception is a tie: where the op's contract does not fix which of two equal inputs wins,
* an id that indexes a value equal to the reference id's value is accepted. Ops whose contract
* breaks ties on the lower id (row_topk, row_topk_merge, pair_argmax, logit_rerank) are exact. */
/* Integer dtypes whose values are ids, counts or offsets. i8 and u8 are quantised codes, which a
* tolerance judges like the values they stand for. */
bool is_index_dtype(uint32_t dt);
/* Where an index output's ties are judged: the input operand its ids index, by row. */
struct TieRule {
const char* op;
const char* output; /* the index operand's name */
const char* input; /* the operand its ids index, row by row */
int lane_stride; /* 2 for an (id, value) pair plane: only even lanes are ids */
};
const TieRule* tie_rule(const std::string& op, const char* output);
/* What an index output's ids point at, for judging a tie at one position. */
struct TieView {
const void* in = nullptr; /* the indexed input, as the kernel read it */
uint32_t in_dtype = 0;
int64_t in_rows = 0, in_width = 0;
int64_t out_width = 1; /* elements per row of the index output */
int lane_stride = 1;
int64_t id_base = 0; /* subtracted from an id before indexing (vocab_off) */
};
/* Whether position `pos` of an index output may hold `got` where the reference holds `want`:
* equal, or (with a tie view) both ids index equal values in the same row. A lane that is not an
* id lane must be equal. */
bool index_matches(const TieView* tie, int64_t pos, int64_t got, int64_t want);
/* ================================================================== the replay's verdict
*
* A replay has the reference reduced to a digest (kfixture.h); the kernel's output is reduced the
* same way here and the two compared. Every quantity feeds one rel_l2-scaled error: the sampled
* positions, the full-tensor norm (a correct first tile followed by zeros) and, in a version-5
* recording, the projection sketch (a localised error the samples miss and the norm cannot see,
* such as a permuted or sign-flipped tile). */
struct Digest {
int64_t n = 0;
double sumsq = 0;
int64_t nonfinite = 0;
std::vector<float> sample;
std::vector<double> sketch;
};
/* The kernel side of a recorded operand: the same reduction the recorder ran, with the sketch only
* when `sketch` (a version-4 recording has none to compare with). */
void digest_of(const float* v, int64_t n, uint64_t seed, bool sketch, Digest* out);
/* The recorded reference of `rec` as a digest. */
Digest digest_of(const KfOperand& rec);
struct OpdVerdict {
double rel = 0; /* the error the verdict uses: the largest of the three below */
double sample_rel = 0, norm_rel = 0, sketch_rel = -1;
double max_abs = 0, max_rel = 0;
int64_t nonfinite_gap = 0; /* sampled finiteness disagreements plus the count difference */
bool index = false; /* compared as ids */
int64_t index_mismatch = 0, ties = 0;
bool vacuous = false; /* both sides identically zero: nothing was checked */
bool bad = false;
};
/* One recorded output against the kernel's digest. `tol` is the operand's tolerance; `exact`
* judges with tolerance 0 (the reference library replaying its own recording). Index dtypes are
* compared at the sampled positions id by id, through `tie` where the op allows ties; positions are
* re-derived from `pos_seed` as the recorder drew them. */
OpdVerdict judge_operand(const KfOperand& rec, const Digest& mine, uint64_t pos_seed, double tol,
bool exact, const TieView* tie);
/* ================================================================== keys */
/* The replay's cap key: the op, the kernel and library that serve it, the domain, the recorded
* parameters, and every operand's dtype and shape. Depth lives in the operand shapes (a KV cache
* of 1024 blocks against 128), not in the parameters, so a key without them collapses the
* attention depth sweep into its shallowest case. */
std::string cap_key(const KfCase& c, const std::string& kernel, const std::string& lib, int dom,
const Geometry& g);
/* The host weight cache's key: the weight's identity seed, its encoding and its plane selection.
* Two weights with one seed can differ in encoding (a bf16 embedding against a two-plane fp8
* lm_head of the same shape). */
uint64_t host_weight_key(const KfOperand& d, size_t k);
/* The device weight cache's key: the host key plus the library and kernel whose layout produced
* the bytes, and their size. */
std::string device_weight_key(const std::string& lib, const std::string& kernel,
const KfOperand& d, size_t k, size_t bytes);
/* ================================================================== memory */
/* What one case may take: three copies of every present operand (the draw, the kernel's copy, a
* re-laid weight or a device copy). -1 when an extent is not positive or the product overflows,
* which a loaded fixture refuses anyway. */
int64_t case_bytes(const std::vector<KfOperand>& opd);
/* The default case budget from /proc/meminfo's text: half of MemAvailable, clamped to
* [512 MiB, 8 GiB]. MemFree is not the budget: page cache counts against it and is reclaimable.
* `avail` gets MemAvailable in bytes, or 0 when the text has none (then the budget is 8 GiB). */
int64_t default_case_budget(const std::string& meminfo, int64_t* avail);
/* ================================================================== red zones */
/* A guarded allocation's margins after a launch: the furthest byte changed before the start (as a
* distance from it) and past the end. Zero and zero is clean. */
struct Overrun { int64_t before = 0, after = 0; };
Overrun scan_margins(const uint8_t* lo, const uint8_t* hi, int64_t red_bytes, uint8_t fill);
/* ================================================================== what a run found */
struct Stats {
int checked = 0, passed = 0, failed = 0, skipped = 0, capped = 0, diverged = 0;
int overrun = 0, guarded = 0, timed = 0;
int fuse_failed = 0;
/* A host kernel that changed an operand it was handed to read. */
int input_written = 0;
/* Both sides identically zero: counted apart from passes, since nothing was checked. */
int vacuous = 0;
/* Skips that mean the fixture and the libraries no longer agree: an operand count or schema
* that moved, the reference without a row for a case it recorded, or describing an output
* differently from its recording. Failures under --strict. */
int stale = 0;
/* Cases no library under test serves: named, never a failure. */
int unserved = 0;
/* Reference results taken from the cache instead of a launch. */
int cached = 0;
double worst = 0;
};
/* 1 when anything failed: a wrong number, an overrun, a fusion that differs from its chain, a
* kernel that wrote its input, and under `strict` a stale fixture. 0 otherwise. */
int exit_code(const Stats& st, bool strict);
/* ================================================================== where the time went */
enum Phase {
PH_LOAD = 0, /* plugins and fixture */
PH_DRAW, /* inputs and weight planes */
PH_HASH, /* input hashes for the reference cache */
PH_LAYOUT, /* weight relayouts */
PH_UPLOAD, /* allocations and host-to-device copies */
PH_LAUNCH, /* the checked launches, per library below */
PH_READBACK, /* device-to-host copies and margins */
PH_COMPARE, /* reductions and verdicts */
PH_CACHE, /* reference cache reads and writes */
PH_TIMING, /* --bench: calibration, warm-up and the timed batches */
PH_REPORT,
PH_N
};
struct Phases {
double s[PH_N] = {};
std::map<std::string, double> launch_by_lib;
void add(Phase p, double sec) { s[p] += sec; }
};
/* Accumulates the time from construction to destruction (or stop()) into one phase. */
class PhaseTimer {
public:
PhaseTimer(Phases* ph, Phase p) : ph_(ph), p_(p), t0_(std::chrono::steady_clock::now()) {}
~PhaseTimer() { stop(); }
double stop();
private:
Phases* ph_;
Phase p_;
std::chrono::steady_clock::time_point t0_;
bool done_ = false;
};
/* "time: draw 1.2 s, launch 4.0 s (libavx 3.1 s, libref 0.9 s), ... of 6.0 s wall". */
std::string phase_line(const Phases& ph, double wall_s);
/* ================================================================== timing
*
* The rules of the timing pass (tools/kbench_timer.cpp), apart from its device calls: statistics
* over per-launch times and when to stop collecting them, how long a batch runs, how many rotated
* copies make every launch read its weights from memory, which operands rotate, the clock
* telemetry's table, the calibration's plausibility check, and the inputs the timing pass draws
* where the correctness draw is not what the engine sees. */
/* Order statistics of per-launch times in microseconds, one per timed batch. */
struct TimeStats {
int n = 0;
double median = -1, min = -1, max = -1;
double p90 = -1; /* nearest rank: the ceil(0.9 n)-th smallest */
/* A distribution-free confidence interval for the median: the order statistics of ranks
* floor(n/2 - 0.98 sqrt(n)) and ceil(n/2 + 1 + 0.98 sqrt(n)), clipped to the sample. Up to
* ten samples that is the whole range, which covers the median with probability
* 1 - 2^(1-n): 95% from six samples on, less below (94% at five, 50% at two). From eleven on,
* one outlier on either side leaves it unchanged. None (-1) for fewer than two samples. */
double ci_lo = -1, ci_hi = -1;
double ci_pct = -1; /* half the interval's width, as a percent of the median */
};
TimeStats time_stats(std::vector<double> v);
/* Whether a case has been timed enough: `max_n` batches, or at least `min_n` whose median's
* interval half-width is within `ci_pct` percent. */
bool timing_done(const std::vector<double>& v, int min_n, int max_n, double ci_pct);
/* The device time one batch should last: a millisecond, and fifty launch floors, so the batch's
* own start and end (two barrier packets) are a small share of it. */
double batch_target_us(double floor_us);
/* Launches in one batch: `fixed` when positive (--bench-iters), else enough to last `target_us` at
* `est_us` a launch. At least one, at most `room` (what fits behind the gate). */
int64_t batch_launches(double est_us, double target_us, int64_t room, int64_t fixed);
/* Why a device time is an order of magnitude rather than a measurement, or "" when it is one. A
* time is a timed batch minus a batch of the in-place restores alone, divided by its launches:
* restores at `restore_pct` >= 75 of the batch leave the kernel a small difference of two large
* times, and a median more than 5% under the back-to-back launch floor, which a dependent
* dispatch cannot beat, shows the difference is biased. -1 for either input means not measured. */
std::string timing_caveat(double median_us, double floor_us, double restore_pct);
/* The distance between rotated copies of an operand: its bytes rounded up to 256, the alignment a
* guarded allocation gives every operand. */
int64_t rotation_stride(int64_t bytes);
/* How many copies of the rotated operands make every launch read them from memory: between two
* uses of one copy, the launches in between read at least `footprint` bytes of other copies, which
* evicts it from every cache smaller than half the footprint. `per_launch` is the bytes one launch
* reads, one copy of each rotated operand. One when that alone reaches the footprint (it evicts
* itself) or the footprint is zero (warm timing). */
int64_t rotation_copies(int64_t per_launch, int64_t footprint);
/* The rotation footprint when --bench-flush does not set one: twice `cache_bytes` (L2 plus the last
* level), and at least 256 MiB, twice the R9700's 8 MiB L2 and 64 MiB last-level cache with room to
* spare. */
int64_t default_footprint(int64_t cache_bytes);
/* Whether an operand rotates in cold timing. Weights and weight tables always: the engine streams
* them once a step. An input from `big_input` bytes on: such an input is state the engine also
* reads once a step (a KV cache, a table), while a smaller one is an activation the previous op
* left in the cache. Outputs never, and in-place operands are restored instead. */
bool rotated(int role, int64_t bytes, int64_t big_input);
/* The order of a weight table's entries for launch `l`: a seeded permutation of [0, n), the same
* for every table of the same size. A launch reads the experts its routing names through a pointer
* table that sends them to these slots, so consecutive launches read different experts' bytes for
* the same routing (a table the size of the footprint is then cold, though one launch reads only
* its routed experts). */
void table_permutation(int64_t n, uint64_t seed, int64_t l, std::vector<int64_t>* out);
/* How many pointer tables a weight table rotated over `copies` copies cycles through: at least 64,
* and a multiple of `copies`, so table l always points into copy l mod copies and launch i, using
* table i mod count, reads the same copy as the other operands' rotation. */
int64_t table_count(int64_t copies);
/* Pointer table `l` of a weight table: `n` pointers, entry e at the base of copy l mod R (`bases`,
* one per copy) plus table_permutation(n, seed, l)[e] slots of `entry` bytes. Appended to `out`. */
void table_pointers(const std::vector<uint64_t>& bases, int64_t n, int64_t entry, uint64_t seed,
int64_t l, std::vector<uint64_t>* out);
/* Rows of each of `buckets` experts out of `total`, skewed as real routing is: Zipf weights with
* exponent 0.5 over the experts in a seeded order (the hottest of 128 takes about six times the mean
* share), at most `cap` each (a token visits an expert once: the op's M), every row placed. */
std::vector<int64_t> skewed_counts(int64_t buckets, int64_t total, int64_t cap, uint64_t seed);
/* An input drawn again for the timing pass, where the correctness draw gives the kernel less (or
* different) work than the engine does and the kernel's time depends on the values. The checked
* launch keeps the recorded draw, so fixtures replay byte for byte. Into `out` (in the operand's
* dtype), true for:
* - an expert histogram's offsets (an index prefix): skewed_counts with the op's M as the cap;
* - an index operand ranging over the op's n_expert (routing choices): each row's ids distinct,
* drawn from the same skewed weights;
* - an index table of rank two or more with as many entries as its range (a block table, drawn
* with repeats): a permutation, as an allocator hands out distinct blocks.
* False, `out` untouched, for every other operand. */
bool timing_input(const KfOperand& d, const Geometry& g, uint64_t seed, std::vector<uint8_t>* out);
/* The SMU's metrics table as the driver exports it (gpu_metrics). */
struct GpuMetrics {
int format = 0, content = 0; /* the header's revisions */
double gfxclk_mhz = -1; /* averaged graphics clock */
double gfxclk_now_mhz = -1; /* instantaneous */
double hotspot_c = -1;
double power_w = -1;
double gfx_busy_pct = -1;
uint64_t throttle = 0; /* the ASIC-independent throttler bits */
};
/* Reads a gpu_metrics table. Only layout v1.3 (RDNA3 and RDNA4 discrete cards, the layout
* scripts/cardclock.py reads and checks against hwmon) is read; any other is refused, so another
* card's table is never misread. A field the firmware reports as 0xFFFF stays -1. */
bool parse_gpu_metrics(const uint8_t* p, size_t n, GpuMetrics* out);
/* "PPT0+TEMP_HOTSPOT" for throttler bits (amdgpu_smu.h SMU_THROTTLER_*_BIT), "" for none. */
std::string throttle_names(uint64_t bits);
/* One size of the calibration's streaming-read probe: GB/s of bytes read, the same buffer reread
* (warm) and a buffer rotated over the footprint (cold). */
struct BwProbe {
int64_t bytes = 0;
double warm_gbs = -1, cold_gbs = -1;
};
/* Why the probes say cold timings would not be cold, or "" when they are consistent. Cold reads
* stream from memory at one rate whatever their size, so a smaller cold probe more than 1.5x as
* fast as the largest means the rotation was served from a cache. The largest probe is as large as
* the footprint, past every cache warm or cold, so its two rates must agree within 1.5x; otherwise
* the clock moved during calibration. A probe without a positive rate failed. */
std::string bandwidth_refusal(const std::vector<BwProbe>& probes);
/* ================================================================== hashing */
/* XXH64 (Collet's xxHash, 64-bit), for input hashes: fast enough to hash every drawn input on
* every run. Not cryptographic. */
uint64_t hash64(const void* p, size_t n, uint64_t seed);
uint64_t hash_combine(uint64_t h, uint64_t v);
uint64_t hash_str(uint64_t h, const std::string& s);
/* A hash of a whole buffer, its 4 MiB blocks hashed on every core and combined in block order:
* the same value at any thread count. Fingerprints both the reference cache's input hash and the
* check that a host kernel left its inputs alone. */
uint64_t fingerprint(const void* p, size_t n);
/* The identity of the code a library runs: the ELF build-ids of the library at `lib_path` and of
* every shared object the process has loaded that is not in `exclude` (other kernel plugins) and
* not the main program, plus the CPU's model and feature flags (libm picks FMA or non-FMA
* routines at load). 0 when the library has no build-id, which disables caching for it. */
uint64_t code_identity(const std::string& lib_path, const std::vector<std::string>& exclude);
/* The build-id note of the loaded object at `path`, as hex; "" when it has none. */
std::string build_id_of(const std::string& path);
/* ================================================================== the reference cache
*
* libref is deterministic and is most of a replay's CPU time, and its answer to a case changes
* only when its code, its inputs or the case change. So its reduced outputs are cached under a key
* of all three: the code identity, a hash of every input byte it was handed (which catches a draw
* or decode change wherever that code lives) and the case itself (op, parameters, operand
* descriptions, sample seeds, the row). The comparison with the recording still runs on every
* hit, so a tolerance or comparison change is never hidden by the cache.
*
* One file per entry, written to a temporary name and renamed. An entry that fails its checksum
* or does not match its key is a miss. */
class RefCache {
public:
/* `dir` empty disables the cache. */
void open(const std::string& dir, uint64_t identity);
bool enabled() const { return on_; }
bool get(uint64_t key, std::vector<Digest>* outs) const;
void put(uint64_t key, const std::vector<Digest>& outs);
int hits() const { return hits_; }
int writes() const { return writes_; }
const std::string& dir() const { return dir_; }
uint64_t identity() const { return id_; }
private:
std::string path_of(uint64_t key) const;
std::string dir_;
uint64_t id_ = 0;
bool on_ = false;
bool warned_ = false;
mutable int hits_ = 0;
int writes_ = 0;
};
/* A case's cache key: the code identity, the row, the case's description and the input hash. */
uint64_t ref_cache_key(uint64_t identity, const std::string& kernel, const KfCase& c,
const Geometry& g, uint64_t input_hash);
/* ================================================================== row coverage ratchet
*
* One file per (fixture, library): the kernel rows a replay of that fixture reached, one per line,
* sorted. A row listed and not reached fails the ratchet, unless every case that would have reached
* it was skipped for memory (it is unknown, not lost). Rows reached and not listed are reported, to
* be added. */
std::set<std::string> read_rows_file(const std::string& path, bool* exists);
int write_rows_file(const std::string& path, const std::set<std::string>& rows);
struct Ratchet {
std::vector<std::string> lost, gained;
};
Ratchet ratchet(const std::set<std::string>& listed, const std::set<std::string>& reached,
const std::set<std::string>& unknown);
/* The ratchet file name for a fixture and library: kbench_rows_<fixture stem>_<library>.txt. */
std::string rows_file_name(const std::string& fixture_path, const std::string& lib);
/* ================================================================== synthetic geometry */
/* Moves `g` into a kernel row's constraints where a single parameter can satisfy one: an EQ value,
* the first IN value, a violated LE or GE edge, the next DIV multiple. Returns true when every
* constraint then holds. Device facts are never invented. */
bool satisfy_constraints(const RadKernelInfo* ki, Geometry* g);
/* ================================================================== skeleton containers */
/* Writes a sparse copy of the container at `src`: the header and every table byte for byte, the
* data region a hole. Opening it gives the same metadata, directory and encodings, so the declare
* phase and a recording (which draws every weight) run on it, while it occupies a few megabytes
* on disk whatever the model's size. RAD_OK, or an error with `err` set. */
int write_skeleton(const std::string& src, const std::string& dst, std::string* err);
} /* namespace kb */
} /* namespace rad */
+936
View File
@@ -0,0 +1,936 @@
/* kbench_timer.cpp -- rad-kbench's timing pass (kbench_timer.h). */
#include "kbench_timer.h"
#include "device/device.h"
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <dirent.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <set>
#include <unistd.h>
namespace rad {
namespace kb {
namespace {
using Clock = std::chrono::steady_clock;
constexpr int64_t kMiB = (int64_t)1 << 20;
/* Untimed launches between the gate and the timed batch: the first after the gate's L2 invalidate
* and the keep-alive copy re-warms the activations, as the previous op leaves them in the engine. */
constexpr int kWarmUnits = 2;
/* The fewest batches a median is taken from (the fewest whose range covers the median with 95%
* confidence), and its interval's target half-width. */
constexpr int kMinReps = 6;
constexpr double kCiPct = 1.0;
/* Batches repeated per case because a throttler came on. */
constexpr int kMaxRetries = 3;
/* The keep-alive copies read the sweep source in pieces into one piece-sized ring, so they leave at
* most this many dirty bytes in the caches for the batch to write back. */
constexpr int64_t kSweepPiece = kMiB;
/* The read probe's pieces: one workgroup of the ranged copy each. */
constexpr int64_t kReadPiece = 16 << 10;
/* Submissions kept free behind a gate for the event records. */
constexpr int64_t kRoomMargin = 8;
/* The device waited at the gate longer than this: the keep-alive copy was too short. */
constexpr double kIdleUs = 20.0;
/* A host row is timed for at most this long. */
constexpr double kHostBudgetS = 2.0;
/* A host batch without restores runs at least this long, so the clock reads are a small share. */
constexpr double kHostBatchUs = 200.0;
/* Events by role. S and G bracket the gate (how long the device waited for the host), R0 and R1
* the restore batch (each restore followed by a floor launch in the kernel's place), E0 and E1
* the timed batch, B0 and B1 one bracketed launch. */
enum { kS = 0, kG, kR0, kR1, kE0, kE1, kB0, kB1 };
double ms_between(RadEvent a, RadEvent b) {
float ms = 0;
return rad_event_elapsed_ms(a, b, &ms) >= 0 ? (double)ms : -1.0;
}
double median_of(std::vector<double> v) {
if (v.empty()) return -1;
return time_stats(std::move(v)).median;
}
/* The OpenMP threads a host library runs on, from the OpenMP runtime the libraries loaded; 0 when
* none is loaded. */
int omp_threads() {
for (const char* lib : { "libgomp.so.1", "libomp.so", "libomp.so.5", "libiomp5.so" }) {
void* h = dlopen(lib, RTLD_NOW | RTLD_NOLOAD);
if (!h) continue;
auto f = (int (*)(void))dlsym(h, "omp_get_max_threads");
const int n = f ? f() : 0;
dlclose(h);
if (n > 0) return n;
}
return 0;
}
std::string read_small(const std::string& path) {
std::string s;
FILE* f = std::fopen(path.c_str(), "r");
if (!f) return s;
char buf[256];
size_t got;
while ((got = std::fread(buf, 1, sizeof buf, f)) > 0 && s.size() < 4096) s.append(buf, got);
std::fclose(f);
while (!s.empty() && (s.back() == '\n' || s.back() == ' ')) s.pop_back();
return s;
}
/* How a case's operands rotated, for the verbose line: "" when nothing did. */
std::string rotation_of(int64_t R, size_t rotated, size_t tables) {
if (!rotated) return std::string();
std::string s = fmt("%lld cop%s", (long long)R, R == 1 ? "y" : "ies");
if (tables) s += fmt(", %zu weight table(s) through pointer tables", tables);
return s;
}
RadArgs args_of(const TimedCase& c, std::vector<RadTensor>& t) {
RadArgs a{};
a.t = t.data();
a.n_t = (int)t.size();
a.p = c.g.params();
a.n_p = c.g.n_params();
a.scratch = c.scratch;
a.scratch_bytes = c.scratch_bytes;
a.rank = 0;
a.world_size = 1;
return a;
}
/* Which operands rotate and how, shared by the device and host halves. */
struct RotPlan {
std::vector<size_t> ops; /* operand indices */
int64_t R = 1; /* copies */
};
RotPlan plan_rotation(const TimedCase& c, int64_t footprint) {
RotPlan p;
if (footprint <= 0) return p;
const int64_t big = footprint / 32;
int64_t per = 0;
for (size_t k = 0; k < c.opd.size(); ++k) {
const TimedOperand& d = c.opd[k];
if (!d.t.data || d.bytes <= 0 || !rotated(d.role, d.bytes, big)) continue;
p.ops.push_back(k);
per += rotation_stride(d.bytes);
}
if (!p.ops.empty()) p.R = rotation_copies(per, footprint);
return p;
}
/* A weight table rotated through pointer tables: stacked [n, ...] with equal entries. */
bool table_form(const TimedOperand& d, int64_t* n, int64_t* entry) {
if (d.role != RAD_OPD_WTAB || d.t.rank < 2 || d.t.shape[0] <= 0 || d.t.stride[0] == 0)
return false;
*n = d.t.shape[0];
if (d.bytes % *n) return false;
*entry = d.bytes / *n;
return true;
}
} /* namespace */
/* ================================================================== the device half */
struct DeviceTimer::Prepared {
TimedCase* c = nullptr;
std::vector<RadTensor> t;
struct Rot { size_t k; uint8_t* arena; int64_t stride; };
struct Tab { size_t k; uint8_t* tables; int64_t n; int64_t count; };
struct Store { void* dst; const void* src; int64_t bytes; };
std::vector<Rot> rot;
std::vector<Tab> tab;
std::vector<Store> restores;
std::vector<void*> frees;
int64_t R = 1;
int64_t next = 0; /* the launch index, continued across batches */
/* Measured behind the gate: submissions a unit (restores plus launch) and a restore set take,
* and the room at the gate. */
int64_t unit_subs = -1, restore_subs = 0, room = 0;
bool gated = true;
};
struct DeviceTimer::Rep {
bool ok = false;
double us = -1; /* a launch, restores subtracted */
double unit_us = -1; /* a unit, restores included: what sizes the next batch */
double restore_pct = -1;
double idle_us = 0;
double clock = -1;
uint64_t throttle = 0; /* throttlers on that were off at idle */
std::string why;
};
DeviceTimer::DeviceTimer(const TimerOpts& o, RadStream s, Phases* ph) : o_(o), s_(s), ph_(ph) {}
DeviceTimer::~DeviceTimer() {
if (s_) (void)rad_stream_sync(s_);
for (Held& h : held_) free_case(h);
for (RadEvent& e : ev_) if (e) rad_event_destroy(e);
for (void* p : { sweep_src_, sweep_dst_, word_ })
if (p) rad_dev_free(p, RAD_MEM_DEVICE);
}
void DeviceTimer::free_case(Held& h) {
for (void* p : h.c.frees) if (p) rad_dev_free(p, RAD_MEM_DEVICE);
h.c.frees.clear();
}
int64_t DeviceTimer::add(TimedCase&& c) {
int64_t extra = 0;
for (const TimedOperand& d : c.opd) {
if (d.role == RAD_OPD_INOUT && d.pristine && d.bytes > 0) extra += d.bytes;
extra += (int64_t)d.variant.size();
}
if (!held_.empty() && held_bytes_ + c.held + extra > o_.budget) flush();
Held h;
h.id = next_id_++;
h.pristine.assign(c.opd.size(), nullptr);
std::string why;
for (size_t k = 0; k < c.opd.size() && why.empty(); ++k) {
TimedOperand& d = c.opd[k];
if (d.role == RAD_OPD_INOUT && d.pristine && d.bytes > 0) {
void* p = rad_dev_alloc(d.bytes, RAD_MEM_DEVICE);
if (!p || rad_memcpy_async(p, d.pristine, d.bytes, s_) < 0) {
why = "no device memory for a pristine copy of an in-place operand";
if (p) rad_dev_free(p, RAD_MEM_DEVICE);
break;
}
c.frees.push_back(p);
h.pristine[k] = p;
}
d.pristine = nullptr;
if (!d.variant.empty()) {
void* p = rad_dev_alloc((int64_t)d.variant.size(), RAD_MEM_DEVICE);
if (!p || rad_memcpy_async(p, d.variant.data(), (int64_t)d.variant.size(), s_) < 0) {
why = "no device memory for a timing input";
if (p) rad_dev_free(p, RAD_MEM_DEVICE);
break;
}
c.frees.push_back(p);
d.t.data = p;
d.bytes = (int64_t)d.variant.size();
}
}
/* The host bytes are the caller's and the variants are about to go. */
if (rad_stream_sync(s_) < 0 && why.empty()) why = std::string("an upload failed: ") +
rad_dev_last_error();
for (TimedOperand& d : c.opd) std::vector<uint8_t>().swap(d.variant);
h.c = std::move(c);
if (!why.empty()) {
Timing t;
t.note = why;
results_[h.id] = t;
free_case(h);
return h.id;
}
h.c.held += extra;
held_bytes_ += h.c.held;
held_.push_back(std::move(h));
return held_.back().id;
}
void DeviceTimer::drop(int64_t id) {
for (auto it = held_.begin(); it != held_.end(); ++it) {
if (it->id != id) continue;
held_bytes_ -= it->c.held;
(void)rad_stream_sync(s_);
free_case(*it);
held_.erase(it);
break;
}
results_.erase(id);
}
const Timing* DeviceTimer::result(int64_t id) const {
const auto it = results_.find(id);
return it == results_.end() ? nullptr : &it->second;
}
double DeviceTimer::clock_now(uint64_t* throttle) {
if (throttle) *throttle = 0;
if (metrics_path_.empty()) return -1;
uint8_t buf[512];
const int fd = ::open(metrics_path_.c_str(), O_RDONLY);
if (fd < 0) return -1;
const ssize_t n = ::read(fd, buf, sizeof buf);
::close(fd);
GpuMetrics m;
if (n <= 0 || !parse_gpu_metrics(buf, (size_t)n, &m)) return -1;
if (throttle) *throttle = m.throttle;
return m.gfxclk_mhz;
}
void DeviceTimer::sweep(int64_t bytes) {
for (int64_t done = 0; done < bytes; done += kSweepPiece) {
if (sweep_off_ + kSweepPiece > sweep_src_bytes_) sweep_off_ = 0;
(void)rad_memcpy_async(sweep_dst_, (const uint8_t*)sweep_src_ + sweep_off_, kSweepPiece, s_);
sweep_off_ += kSweepPiece;
}
}
void DeviceTimer::setup() {
set_up_ = true;
RadDeviceProps props{};
const bool have_props = rad_dev_props(0, &props) >= 0;
const bool host = have_props && props.is_host_backend;
const int64_t llc = host ? host_llc_bytes() : 0;
footprint_ = o_.footprint >= 0 ? o_.footprint : default_footprint(llc);
scale_ = footprint_ > 0 ? footprint_ : default_footprint(llc);
std::string fail;
for (RadEvent& e : ev_)
if (!e && rad_event_create_as(&e, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT) < 0)
fail = std::string("no events: ") + rad_dev_last_error();
sweep_src_bytes_ = std::max(scale_, kSweepPiece);
if (fail.empty()) {
sweep_src_ = rad_dev_alloc(sweep_src_bytes_, RAD_MEM_DEVICE);
sweep_dst_ = rad_dev_alloc(kSweepPiece, RAD_MEM_DEVICE);
word_ = rad_dev_alloc(256, RAD_MEM_DEVICE);
if (!sweep_src_ || !sweep_dst_ || !word_)
fail = "no device memory for the keep-alive copy (" + humanb(sweep_src_bytes_) + ")";
}
if (fail.empty() && (rad_memset_async(sweep_src_, 0, sweep_src_bytes_, s_) < 0 ||
rad_stream_sync(s_) < 0))
fail = std::string("the keep-alive source could not be written: ") + rad_dev_last_error();
if (!fail.empty()) {
setup_failed_ = true;
withheld_ = fail;
header_.push_back("timing: " + fail);
return;
}
sweep_bytes_ = std::min<int64_t>(64 * kMiB, scale_);
sweep_max_ = std::min<int64_t>(std::max<int64_t>(4 * scale_, 4 * kMiB), (int64_t)1 << 30);
const std::string pci = dev_pci_address(0);
if (!pci.empty()) {
metrics_path_ = "/sys/bus/pci/devices/" + pci + "/gpu_metrics";
if (clock_now(&idle_throttle_) < 0) metrics_path_.clear();
}
header_.push_back(fmt("device: %s (%s), the %s backend", have_props ? props.name : "?",
have_props ? props.arch : "?", device_backend_name()));
if (footprint_ > 0)
header_.push_back(fmt("cold: each launch reads its weights, weight tables and inputs of %s "
"or more from one of a set of copies spanning %s, so from memory; "
"smaller inputs stay warm, as the previous op leaves them; in-place "
"operands are restored before every launch and the restores' own "
"time subtracted", humanb(footprint_ / 32).c_str(),
humanb(footprint_).c_str()));
else
header_.push_back("warm: every launch rereads the same operands, so whatever fits in the "
"caches is read from them; in-place operands are restored before every "
"launch and the restores' own time subtracted");
if (o_.warm_ms > 0) warm_up();
uint64_t loaded = 0;
warm_clock_ = clock_now(&loaded);
if (o_.warm_ms > 0) load_throttle_ = loaded & ~idle_throttle_;
calibrate();
if (!metrics_path_.empty()) {
const std::string idle = throttle_names(idle_throttle_);
const std::string load = throttle_names(load_throttle_);
header_.push_back(fmt("clock: %.0f MHz averaged graphics clock after a %d ms warm-up "
"(gpu_metrics)%s%s; a batch during which another throttler came on "
"is repeated", warm_clock_, o_.warm_ms,
idle.empty() ? "" : ("; on at idle, not counted: " + idle).c_str(),
load.empty() ? "" : ("; on under the warm-up's load, binding "
"throughout and not counted: " + load).c_str()));
} else {
header_.push_back("clock: not read (no gpu_metrics table for this device)");
}
}
/* Sustained load for --bench-warm-ms: keep-alive copies and the held cases' own launches, one
* round always queued behind the one the host waits for, so the card never idles meanwhile. */
void DeviceTimer::warm_up() {
const auto t0 = Clock::now();
size_t ci = 0;
for (int64_t round = 0;
std::chrono::duration<double, std::milli>(Clock::now() - t0).count() < o_.warm_ms;
++round) {
sweep(scale_);
if (!held_.empty()) {
/* In-place operands restored as in the timed batches: a state applied over and over
* can leave the range its kernel addresses. */
Held& h = held_[ci++ % held_.size()];
std::vector<RadTensor> t;
for (const TimedOperand& d : h.c.opd) t.push_back(d.t);
const RadArgs a = args_of(h.c, t);
for (int i = 0; i < 8; ++i) {
for (size_t k = 0; k < h.c.opd.size(); ++k)
if (h.pristine[k])
(void)rad_memcpy_async(h.c.opd[k].t.data, h.pristine[k], h.c.opd[k].bytes,
s_);
if (h.c.info->launch(&a, s_) < 0) break;
}
}
(void)rad_event_record(ev_[kB0 + (round & 1)], s_);
if (round > 0 && rad_event_sync(ev_[kB0 + ((round - 1) & 1)]) < 0) break;
}
(void)rad_stream_sync(s_);
(void)rad_dev_last_error();
last_busy_ = Clock::now();
}
/* Reads of `bytes` from src + i * bytes for i cycling over `copies`, as one ranged copy each
* (`ranges`, device memory) whose pieces all land in the sweep's ring: the writes stay in the
* cache, so the rate is the read stream's. GB/s of bytes read, the median of gated batches. */
double DeviceTimer::read_rate(const uint8_t* src, int64_t bytes, int64_t copies, const void* ranges,
int ranges_n) {
std::vector<double> gbs;
int64_t i = 0, n = 2;
const double target = batch_target_us(floor_us_);
auto read = [&]() {
const uint8_t* from = src + (i++ % copies) * bytes;
return rad_memcpy_ranges_async(sweep_dst_, from, 0, (const RadCopyRange*)ranges, ranges_n,
s_);
};
for (int r = 0; r < 12; ++r) {
void* gate = nullptr;
sweep(sweep_bytes_);
if (rad_stream_gate(s_, &gate) < 0) return -1;
const int64_t room = rad_gate_room(s_) - kRoomMargin - kWarmUnits;
int rc = RAD_OK;
for (int w = 0; w < kWarmUnits && rc >= 0; ++w) rc = read();
(void)rad_event_record(ev_[kE0], s_);
for (int64_t j = 0; j < n && rc >= 0; ++j) rc = read();
(void)rad_event_record(ev_[kE1], s_);
(void)rad_gate_open(gate);
if (rad_stream_sync(s_) < 0 || rc < 0) return -1;
const double ms = ms_between(ev_[kE0], ev_[kE1]);
if (ms <= 0) return -1;
if (r > 0) gbs.push_back((double)bytes * (double)n / (ms * 1e-3) / 1e9);
n = batch_launches(ms * 1e3 / (double)n, target, room, 0);
if (timing_done(gbs, kMinReps, 10, kCiPct)) break;
}
return median_of(gbs);
}
void DeviceTimer::calibrate() {
/* The launch floor: the cheapest kernel there is, the backend's own 4-byte fill. Back to back
* is what a launch costs inside a batch; bracketed (alone between two events) is what it costs
* timed one launch at a time. */
{
std::vector<double> b2b, bracketed;
int64_t n = 256;
for (int r = 0; r < 12 && (int)b2b.size() < 10; ++r) {
void* gate = nullptr;
sweep(sweep_bytes_);
if (rad_stream_gate(s_, &gate) < 0) break;
n = std::min<int64_t>(n, rad_gate_room(s_) - kRoomMargin - kWarmUnits);
int rc = RAD_OK;
for (int w = 0; w < kWarmUnits; ++w) rc |= rad_memset_async(word_, w, 4, s_);
(void)rad_event_record(ev_[kE0], s_);
for (int64_t j = 0; j < n; ++j) rc |= rad_memset_async(word_, (int)(j & 0xff), 4, s_);
(void)rad_event_record(ev_[kE1], s_);
(void)rad_event_record(ev_[kB0], s_);
rc |= rad_memset_async(word_, 1, 4, s_);
(void)rad_event_record(ev_[kB1], s_);
(void)rad_gate_open(gate);
if (rad_stream_sync(s_) < 0 || rc != RAD_OK) break;
const double ms = ms_between(ev_[kE0], ev_[kE1]);
const double one = ms_between(ev_[kB0], ev_[kB1]);
if (ms > 0) b2b.push_back(ms * 1e3 / (double)n);
if (one > 0) bracketed.push_back(one * 1e3);
if (timing_done(b2b, kMinReps, 10, kCiPct) && (int)bracketed.size() >= kMinReps) break;
}
floor_us_ = median_of(b2b);
floor_bracketed_us_ = median_of(bracketed);
header_.push_back(fmt("launch floor: %.2f us a launch back to back in a batch, %.2f us "
"alone between two events (the backend's own 4-byte fill, the "
"cheapest kernel a tool can launch); a batch lasts at least %.0f us",
floor_us_, floor_bracketed_us_, batch_target_us(floor_us_)));
}
/* Streaming-read bandwidth at four sizes up to the footprint, warm (one buffer reread) and
* cold (rotated over the footprint). The probes check that cold reads are cold, so warm
* timing, which takes none, skips them. */
if (footprint_ <= 0) {
header_.push_back("read bandwidth: not probed (warm timing reads nothing cold)");
if (floor_us_ <= 0) {
withheld_ = "the launch floor could not be measured";
header_.push_back("timings withheld: " + withheld_);
}
return;
}
std::vector<BwProbe> probes;
int64_t last = 0;
for (const int64_t div : { (int64_t)64, (int64_t)16, (int64_t)4, (int64_t)1 }) {
const int64_t bytes = std::max<int64_t>(64 << 10, (scale_ / div) & ~(int64_t)0xFFFF);
if (bytes == last) continue;
last = bytes;
BwProbe p;
p.bytes = bytes;
/* Pieces of 16 KiB, one workgroup each, cycling through the 1 MiB ring. */
std::vector<RadCopyRange> pieces;
for (int64_t off = 0; off < bytes; off += kReadPiece)
pieces.push_back({ off, off % kSweepPiece, std::min(kReadPiece, bytes - off) });
const int64_t list = (int64_t)(pieces.size() * sizeof(RadCopyRange));
const int64_t R = rotation_copies(bytes, scale_);
uint8_t* src = (uint8_t*)rad_dev_alloc(R * bytes, RAD_MEM_DEVICE);
void* ranges = rad_dev_alloc(list, RAD_MEM_DEVICE);
if (src && ranges && rad_memset_async(src, 1, R * bytes, s_) >= 0 &&
rad_memcpy_async(ranges, pieces.data(), list, s_) >= 0 && rad_stream_sync(s_) >= 0) {
p.warm_gbs = read_rate(src, bytes, 1, ranges, (int)pieces.size());
p.cold_gbs = read_rate(src, bytes, R, ranges, (int)pieces.size());
}
if (src) rad_dev_free(src, RAD_MEM_DEVICE);
if (ranges) rad_dev_free(ranges, RAD_MEM_DEVICE);
probes.push_back(p);
}
std::string bw = "read bandwidth (ranged copies into a 1 MiB ring, so the writes stay in the "
"cache), warm / cold:";
for (const BwProbe& p : probes)
bw += fmt(" %s %.0f / %.0f GB/s;", humanb(p.bytes).c_str(), p.warm_gbs, p.cold_gbs);
bw.pop_back();
header_.push_back(bw);
RadDeviceProps props{};
const bool host = rad_dev_props(0, &props) >= 0 && props.is_host_backend;
const std::string why = bandwidth_refusal(probes);
if (!why.empty() && !host) {
withheld_ = why;
header_.push_back("timings withheld: " + why);
} else if (!why.empty()) {
header_.push_back("(host backend: no device caches to defeat, so the check does not "
"apply: " + why + ")");
}
if (floor_us_ <= 0 && withheld_.empty()) {
withheld_ = "the launch floor could not be measured";
header_.push_back("timings withheld: " + withheld_);
}
}
bool DeviceTimer::prepare(Held& h, Prepared* p, std::string* why) {
TimedCase& c = h.c;
p->c = &c;
for (const TimedOperand& d : c.opd) p->t.push_back(d.t);
for (size_t k = 0; k < c.opd.size(); ++k)
if (h.pristine[k]) p->restores.push_back({ c.opd[k].t.data, h.pristine[k], c.opd[k].bytes });
const RotPlan plan = plan_rotation(c, footprint_);
p->R = plan.R;
for (size_t k : plan.ops) {
const TimedOperand& d = c.opd[k];
const int64_t stride = rotation_stride(d.bytes);
uint8_t* base = (uint8_t*)d.t.data;
uint8_t* arena = nullptr;
if (p->R > 1) {
arena = (uint8_t*)rad_dev_alloc(p->R * stride, RAD_MEM_DEVICE);
if (!arena) {
*why = "no device memory for " + std::to_string(p->R) + " rotated copies of " +
humanb(d.bytes);
return false;
}
p->frees.push_back(arena);
/* The original into the first copy, then the filled prefix doubled. */
int rc = rad_memcpy_async(arena, base, d.bytes, s_);
for (int64_t have = 1; have < p->R && rc >= 0; have *= 2)
rc = rad_memcpy_async(arena + have * stride, arena,
std::min(have, p->R - have) * stride, s_);
if (rc < 0) { *why = "the rotated copies could not be written"; return false; }
}
int64_t n = 0, entry = 0;
if (table_form(d, &n, &entry)) {
const int64_t count = table_count(p->R);
std::vector<uint64_t> bases;
for (int64_t r = 0; r < p->R; ++r)
bases.push_back((uint64_t)(uintptr_t)(arena ? arena + r * stride : base));
std::vector<uint64_t> ptr;
ptr.reserve((size_t)(count * n));
for (int64_t l = 0; l < count; ++l) table_pointers(bases, n, entry, c.seed, l, &ptr);
uint8_t* tables = (uint8_t*)rad_dev_alloc(count * n * 8, RAD_MEM_DEVICE);
if (!tables) { *why = "no device memory for the weight table's pointer tables"; return false; }
p->frees.push_back(tables);
if (rad_memcpy_async(tables, ptr.data(), count * n * 8, s_) < 0 ||
rad_stream_sync(s_) < 0) {
*why = "the pointer tables could not be written";
return false;
}
p->t[k].stride[0] = 0;
p->tab.push_back({ k, tables, n, count });
} else if (arena) {
p->rot.push_back({ k, arena, stride });
}
}
if (rad_stream_sync(s_) < 0) { *why = std::string("setup failed: ") + rad_dev_last_error(); return false; }
return true;
}
void DeviceTimer::release(Prepared* p) {
(void)rad_stream_sync(s_);
for (void* f : p->frees) rad_dev_free(f, RAD_MEM_DEVICE);
p->frees.clear();
}
void DeviceTimer::unit(Prepared& p, bool restore, int* rc) {
if (restore)
for (const Prepared::Store& r : p.restores)
if (rad_memcpy_async(r.dst, r.src, r.bytes, s_) < 0) { *rc = RAD_E_DEVICE; return; }
const int64_t i = p.next++;
for (const Prepared::Rot& r : p.rot) p.t[r.k].data = r.arena + (i % p.R) * r.stride;
for (const Prepared::Tab& b : p.tab) p.t[b.k].data = b.tables + (i % b.count) * b.n * 8;
const RadArgs a = args_of(*p.c, p.t);
const int s = p.c->info->launch(&a, s_);
if (s < 0) *rc = s;
}
DeviceTimer::Rep DeviceTimer::rep(Prepared& p, int64_t n, bool gated) {
Rep r;
void* gate = nullptr;
int rc = RAD_OK;
sweep(sweep_bytes_);
if (gated) {
(void)rad_event_record(ev_[kS], s_);
if (rad_stream_gate(s_, &gate) < 0) {
r.why = std::string("no gate: ") + rad_dev_last_error();
return r;
}
(void)rad_event_record(ev_[kG], s_);
}
const int64_t room0 = gated ? rad_gate_room(s_) : 0;
if (!p.restores.empty()) {
/* The baseline the restores are subtracted with: each restore set followed, as in the
* timed batch, by a dependent launch, here the floor's fill. Restores alone back to back
* pipeline differently from a restore feeding a launch, and the difference came out under
* the launch floor for kernels that are mostly restore. The fill's own cost, the floor,
* is added back below. */
(void)rad_event_record(ev_[kR0], s_);
for (int64_t j = 0; j < n && rc >= 0; ++j) {
for (const Prepared::Store& s : p.restores)
if (rad_memcpy_async(s.dst, s.src, s.bytes, s_) < 0) rc = RAD_E_DEVICE;
if (rc >= 0 && rad_memset_async(word_, (int)(j & 0xff), 4, s_) < 0) rc = RAD_E_DEVICE;
}
(void)rad_event_record(ev_[kR1], s_);
}
const int64_t room1 = gated ? rad_gate_room(s_) : 0;
for (int w = 0; w < kWarmUnits && rc >= 0; ++w) unit(p, true, &rc);
const int64_t room2 = gated ? rad_gate_room(s_) : 0;
if (rc >= 0) (void)rad_event_record(ev_[kE0], s_);
for (int64_t j = 0; j < n && rc >= 0; ++j) unit(p, true, &rc);
if (rc >= 0) (void)rad_event_record(ev_[kE1], s_);
if (gate) (void)rad_gate_open(gate);
const int sync = rad_stream_sync(s_);
if (rc < 0 || sync < 0) {
const char* e = rad_dev_last_error();
r.why = *e ? e : rad_strerror(rc < 0 ? rc : sync);
return r;
}
if (gated) {
/* Rounded up: on the host backend the worker may take the gate's own task between two
* reads, which frees one slot. */
const int64_t rs = room0 - room1 - (p.restores.empty() ? 0 : 2);
p.restore_subs = p.restores.empty() || n <= 0 ? 0 : std::max<int64_t>(0, (rs + n - 1) / n);
p.unit_subs = std::max<int64_t>(0, (room1 - room2 + kWarmUnits - 1) / kWarmUnits);
p.room = room0;
}
const double tb = ms_between(ev_[kE0], ev_[kE1]);
const double tr = p.restores.empty() ? 0.0 : ms_between(ev_[kR0], ev_[kR1]);
if (tb < 0 || tr < 0) {
r.why = "the events carry no timestamps";
return r;
}
r.unit_us = tb * 1e3 / (double)n;
r.us = (tb - tr) * 1e3 / (double)n + (p.restores.empty() ? 0.0 : floor_us_);
/* The restores' share of the timed batch: the baseline's floor launches stand in for the
* kernel, so they are not restore time. */
r.restore_pct = p.restores.empty() || tb <= 0
? -1
: 100.0 * std::max(0.0, tr - (double)n * floor_us_ * 1e-3) / tb;
r.idle_us = gated ? std::max(0.0, ms_between(ev_[kS], ev_[kG]) * 1e3) : 0.0;
uint64_t thr = 0;
r.clock = clock_now(&thr);
r.throttle = thr & ~(idle_throttle_ | load_throttle_);
r.ok = true;
return r;
}
void DeviceTimer::time_case(Held& h) {
Timing out;
Prepared p;
std::string why;
const auto t0 = Clock::now();
if (!prepare(h, &p, &why)) {
out.note = why;
results_[h.id] = out;
release(&p);
free_case(h);
return;
}
/* A pilot batch of two sizes the rest and measures what a unit takes behind the gate. A launch
* that cannot run behind a gate (it waits on its own stream: a host-backend device row) is
* timed without one, and says so. */
const int64_t pilot = 2;
Rep r = rep(p, pilot, true);
if (!r.ok) {
p.gated = false;
out.note = r.why.find("closed gate") != std::string::npos
? "ungated: the launch waits on its own stream, which a gate holds"
: "ungated: behind a gate, " + r.why;
r = rep(p, pilot, false);
}
std::vector<double> us, clocks, restore;
double est = r.unit_us;
const double target = batch_target_us(floor_us_);
const int max_reps = std::max(1, o_.max_reps);
while (r.ok) {
int64_t room = 0;
if (p.gated && p.unit_subs > 0)
room = (p.room - kRoomMargin - kWarmUnits * p.unit_subs) /
(p.unit_subs + p.restore_subs);
const int64_t n = batch_launches(est, target, p.gated && p.unit_subs > 0 ? std::max<int64_t>(room, 1) : 0,
o_.fixed);
r = rep(p, n, p.gated);
if (!r.ok) break;
if (r.idle_us > kIdleUs && p.gated) sweep_bytes_ = std::min(2 * sweep_bytes_, sweep_max_);
if (r.throttle) {
if (out.retried < kMaxRetries) { ++out.retried; continue; }
out.note += std::string(out.note.empty() ? "" : "; ") + "throttled (" +
throttle_names(r.throttle) + ") after " + std::to_string(kMaxRetries) +
" retries";
}
us.push_back(r.us);
if (r.clock > 0) clocks.push_back(r.clock);
if (r.restore_pct >= 0) restore.push_back(r.restore_pct);
if (r.unit_us > 0) est = r.unit_us;
if (timing_done(us, std::min(kMinReps, max_reps), max_reps, kCiPct)) break;
}
if (!r.ok)
out.note += std::string(out.note.empty() ? "" : "; ") +
(us.empty() ? "timing failed: " : "stopped early: ") + r.why;
out.st = time_stats(us);
out.clock_mhz = median_of(clocks);
out.restore_pct = median_of(restore);
out.gated = p.gated && out.st.n > 0;
out.rotation = rotation_of(p.R, p.rot.size() + p.tab.size(), p.tab.size());
if (!p.restores.empty() && out.st.n > 0 && out.st.median <= 0) {
out.note += std::string(out.note.empty() ? "" : "; ") +
"restore-dominated: the in-place restores took the whole batch";
} else if (out.st.n > 0) {
const std::string c = timing_caveat(out.st.median, floor_us_,
p.restores.empty() ? -1.0 : out.restore_pct);
if (!c.empty()) out.note += std::string(out.note.empty() ? "" : "; ") + c;
}
results_[h.id] = out;
release(&p);
free_case(h);
if (o_.verbose)
std::printf(" timed %-60s %9.2f us n=%d ci=%.1f%% %s%s%s%s%.1f s\n",
h.c.what.c_str(), out.st.median, out.st.n, out.st.ci_pct,
out.gated ? "gated" : "ungated", out.rotation.empty() ? "" : ", ",
out.rotation.c_str(), out.note.empty() ? " " : (" " + out.note + " ").c_str(),
std::chrono::duration<double>(Clock::now() - t0).count());
}
void DeviceTimer::flush() {
if (held_.empty()) return;
PhaseTimer pt(ph_, PH_TIMING);
const bool first = !set_up_;
if (first) setup();
if (!withheld_.empty()) {
for (Held& h : held_) {
Timing t;
t.note = "withheld: " + withheld_;
results_[h.id] = t;
free_case(h);
}
held_.clear();
held_bytes_ = 0;
return;
}
/* The correctness work since the last pass left the card idle long enough to drop its clock. */
if (!first && o_.warm_ms > 0 &&
std::chrono::duration<double, std::milli>(Clock::now() - last_busy_).count() > 200.0)
warm_up();
for (Held& h : held_) time_case(h);
held_.clear();
held_bytes_ = 0;
last_busy_ = Clock::now();
}
/* ================================================================== the host half */
Timing time_host(const TimedCase& c, const TimerOpts& o, int64_t footprint, double checked_s) {
Timing out;
out.threads = omp_threads();
const size_t nk = c.opd.size();
std::vector<RadTensor> t(nk);
/* The timing draws, and private copies of everything the launch writes: the caller's
* buffers hold the checked launch's output, which a comparison may still read. */
std::vector<std::vector<uint8_t>> variants(nk), written(nk);
struct Store { void* dst; const void* src; int64_t bytes; };
std::vector<Store> restores;
for (size_t k = 0; k < nk; ++k) {
const TimedOperand& d = c.opd[k];
t[k] = d.t;
if (!d.variant.empty()) {
variants[k] = d.variant;
t[k].data = variants[k].data();
}
if ((d.role == RAD_OPD_OUT || d.role == RAD_OPD_INOUT) && d.t.data && d.bytes > 0) {
written[k].assign((const uint8_t*)d.t.data, (const uint8_t*)d.t.data + d.bytes);
t[k].data = written[k].data();
}
if (d.role == RAD_OPD_INOUT && d.pristine && d.bytes > 0)
restores.push_back({ t[k].data, d.pristine, d.bytes });
}
/* Rotation, as on the device: copies in page-aligned host memory, weight tables through
* pointer tables. */
struct Owned {
std::vector<void*> p;
~Owned() { for (void* x : p) std::free(x); }
} owned;
struct Rot { size_t k; uint8_t* arena; int64_t stride; };
struct Tab { size_t k; std::vector<uint64_t> ptr; int64_t n; int64_t count; };
std::vector<Rot> rot;
std::vector<Tab> tab;
TimedCase sized = c; /* the variant sizes, for the plan */
for (size_t k = 0; k < nk; ++k)
if (!variants[k].empty()) {
sized.opd[k].t.data = variants[k].data();
sized.opd[k].bytes = (int64_t)variants[k].size();
}
const RotPlan plan = plan_rotation(sized, footprint);
for (size_t k : plan.ops) {
const TimedOperand& d = sized.opd[k];
const int64_t stride = rotation_stride(d.bytes);
uint8_t* base = (uint8_t*)d.t.data;
uint8_t* arena = nullptr;
if (plan.R > 1) {
arena = (uint8_t*)std::aligned_alloc(4096, (size_t)((plan.R * stride + 4095) & ~(int64_t)4095));
if (!arena) {
out.note = "no memory for " + std::to_string(plan.R) + " rotated copies of " +
humanb(d.bytes);
return out;
}
owned.p.push_back(arena);
std::memcpy(arena, base, (size_t)d.bytes);
for (int64_t have = 1; have < plan.R; have *= 2)
std::memcpy(arena + have * stride, arena,
(size_t)(std::min(have, plan.R - have) * stride));
}
int64_t n = 0, entry = 0;
if (table_form(d, &n, &entry)) {
Tab b;
b.k = k;
b.n = n;
b.count = table_count(plan.R);
std::vector<uint64_t> bases;
for (int64_t r = 0; r < plan.R; ++r)
bases.push_back((uint64_t)(uintptr_t)(arena ? arena + r * stride : base));
for (int64_t l = 0; l < b.count; ++l) table_pointers(bases, n, entry, c.seed, l, &b.ptr);
t[k].stride[0] = 0;
tab.push_back(std::move(b));
} else if (arena) {
rot.push_back({ k, arena, stride });
}
}
int64_t next = 0;
auto launch = [&]() -> int {
const int64_t i = next++;
for (const Rot& r : rot) t[r.k].data = r.arena + (i % plan.R) * r.stride;
for (const Tab& b : tab) t[b.k].data = (void*)(b.ptr.data() + (i % b.count) * b.n);
const RadArgs a = args_of(c, t);
return c.info->launch(&a, nullptr);
};
auto restore = [&]() {
for (const Store& s : restores) std::memcpy(s.dst, s.src, (size_t)s.bytes);
};
double est_us = checked_s * 1e6;
if (checked_s < 1.0) {
restore();
const auto w0 = Clock::now();
if (launch() < 0) {
out.note = "timing failed: the launch refused";
return out;
}
est_us = std::chrono::duration<double, std::micro>(Clock::now() - w0).count();
}
const bool batched = restores.empty();
const int max_reps = std::max(1, o.max_reps);
std::vector<double> us;
const auto start = Clock::now();
for (;;) {
const int64_t b = batched ? batch_launches(est_us, kHostBatchUs, 0, o.fixed) : 1;
if (!batched) restore();
const auto t0 = Clock::now();
for (int64_t j = 0; j < b; ++j)
if (launch() < 0) {
out.note = "timing failed: the launch refused";
out.st = time_stats(us);
return out;
}
const double el = std::chrono::duration<double, std::micro>(Clock::now() - t0).count();
us.push_back(el / (double)b);
est_us = el / (double)b;
if (timing_done(us, std::min(kMinReps, max_reps), max_reps, kCiPct)) break;
if (std::chrono::duration<double>(Clock::now() - start).count() > kHostBudgetS) {
if ((int)us.size() < std::min(kMinReps, max_reps))
out.note = fmt("%zu timed launch(es) within the %.0f s host budget", us.size(),
kHostBudgetS);
break;
}
}
out.st = time_stats(us);
out.rotation = rotation_of(plan.R, rot.size() + tab.size(), tab.size());
if (o.verbose)
std::printf(" timed %-60s %9.2f us n=%d ci=%.1f%% %d thread(s)%s%s%s%s\n",
c.what.c_str(), out.st.median, out.st.n, out.st.ci_pct, out.threads,
out.rotation.empty() ? "" : ", ", out.rotation.c_str(),
out.note.empty() ? "" : " ", out.note.c_str());
return out;
}
int64_t host_llc_bytes() {
/* Every cache index of every CPU at the highest level, each distinct instance (by the CPUs
* sharing it) counted once. */
std::set<std::string> seen;
int64_t total = 0;
int top = 0;
std::vector<std::pair<int, std::pair<std::string, int64_t>>> found;
DIR* d = opendir("/sys/devices/system/cpu");
if (!d) return 0;
while (dirent* e = readdir(d)) {
if (std::strncmp(e->d_name, "cpu", 3) != 0 || !std::isdigit((unsigned char)e->d_name[3]))
continue;
for (int idx = 0; idx < 8; ++idx) {
const std::string base = std::string("/sys/devices/system/cpu/") + e->d_name +
"/cache/index" + std::to_string(idx) + "/";
const std::string level = read_small(base + "level");
if (level.empty()) break;
const std::string size = read_small(base + "size");
const std::string shared = read_small(base + "shared_cpu_list");
char* end = nullptr;
const long long v = std::strtoll(size.c_str(), &end, 10);
if (v <= 0) continue;
const int64_t bytes = (int64_t)v * (end && (*end == 'K' || *end == 'k') ? 1024
: end && (*end == 'M' || *end == 'm') ? kMiB : 1);
const int lv = std::atoi(level.c_str());
top = std::max(top, lv);
found.push_back({ lv, { shared, bytes } });
}
}
closedir(d);
for (const auto& [lv, f] : found) {
if (lv != top || !seen.insert(f.first).second) continue;
total += f.second;
}
return total;
}
} /* namespace kb */
} /* namespace rad */
+167
View File
@@ -0,0 +1,167 @@
/* kbench_timer.h -- rad-kbench's timing pass (--bench).
*
* Correctness runs first. A device case that passes is handed to the DeviceTimer with its operands
* still on the device, and timed later, back to back with the other passing cases, after one
* sustained warm-up, with no host work between its batches. A host case is timed where it was
* checked (time_host): the CPU needs no warm-up the correctness work would undo.
*
* What a device time is: device timestamps around a batch of back-to-back launches, divided by the
* launch count. The batch is queued behind a gate (rad_stream_gate) the host opens once all of it
* is queued, so neither the host's submission rate nor its synchronisation is in the interval; a
* keep-alive copy runs ahead of the gate so the device is not idle (and its clock not falling)
* while the host submits. Cold timing rotates the weights over copies spanning the footprint, so
* every launch reads them from memory; in-place operands are restored from a pristine copy before
* every launch, and the restores' own time, measured in the same window, is subtracted. Each case
* runs until its median is known to 1% or the rep cap; a batch during which a throttler came on
* that was off at idle and after the warm-up is discarded and repeated. The rules are pure
* functions in kbench_core.h.
*/
#pragma once
#include "kbench_core.h"
#include "rad_abi.h"
#include "rad_device.h"
#include <chrono>
#include <map>
#include <string>
#include <vector>
namespace rad {
namespace kb {
struct TimerOpts {
int64_t footprint = -1; /* rotation footprint in bytes: 0 warm, < 0 the default */
int fixed = 0; /* --bench-iters: launches a batch; 0 sizes each batch */
int max_reps = 20; /* --bench-reps: the most batches a case takes */
int warm_ms = 2000; /* --bench-warm-ms: sustained load before each timing pass */
int64_t budget = 0; /* device bytes held for timing before a timing pass runs */
bool verbose = false;
};
/* A timed case's numbers. */
struct Timing {
TimeStats st; /* microseconds a launch */
double clock_mhz = -1; /* median of the batches' averaged graphics clock */
double restore_pct = -1; /* in-place restores, as a percent of the timed batch */
int threads = 0; /* host rows: the OpenMP threads the library runs on */
int retried = 0; /* batches repeated because a throttler came on */
bool gated = false; /* a device case timed behind the gate */
std::string rotation; /* "33 copies, 2 weight table(s) through pointer tables" */
std::string note; /* why a number is missing or worth less */
};
/* One operand as the checked launch saw it. */
struct TimedOperand {
RadTensor t{}; /* device pointers for a device row */
int role = 0;
int64_t bytes = 0; /* the buffer t.data points at */
/* An in-place operand's bytes before the checked launch, host memory, read during add() or
* time_host only. */
const uint8_t* pristine = nullptr;
/* An input's timing draw (kb::timing_input), host memory; empty for the recorded draw. */
std::vector<uint8_t> variant;
};
struct TimedCase {
const RadKernelInfo* info = nullptr;
Geometry g;
std::vector<TimedOperand> opd;
void* scratch = nullptr;
int64_t scratch_bytes = 0;
/* Device allocations (rad_dev_alloc, RAD_MEM_DEVICE) the timer frees once the case is timed. */
std::vector<void*> frees;
int64_t held = 0; /* their bytes, against the timer's budget */
uint64_t seed = 0; /* for the weight tables' permutations */
std::string what; /* for verbose lines */
};
/* The device half: holds passing cases and times them in passes. Not thread-safe; one stream. */
class DeviceTimer {
public:
DeviceTimer(const TimerOpts& o, RadStream s, Phases* ph);
~DeviceTimer();
DeviceTimer(const DeviceTimer&) = delete;
DeviceTimer& operator=(const DeviceTimer&) = delete;
/* Takes the case over (its allocations included) and returns the id its Timing will have. A
* case that would take the held bytes past the budget first times what is held. */
int64_t add(TimedCase&& c);
/* Times every held case and frees them. */
void flush();
/* Forgets a case: frees it if still held, and drops its result. For a case whose verdict,
* reached after it was handed over, says it is not worth timing. */
void drop(int64_t id);
/* The result for an id, after the flush that timed it; null before. */
const Timing* result(int64_t id) const;
/* For the report header: how the times were taken, and the calibration. */
const std::vector<std::string>& header() const { return header_; }
/* Non-empty when the calibration says cold timings would not be cold: no case is timed. */
const std::string& withheld() const { return withheld_; }
bool calibrated() const { return set_up_; }
private:
struct Prepared;
struct Rep;
struct Held {
int64_t id = 0;
TimedCase c;
std::vector<void*> pristine; /* per operand: its device copy before the checked launch */
};
void setup();
void warm_up();
void calibrate();
void sweep(int64_t bytes);
bool prepare(Held& h, Prepared* p, std::string* why);
void release(Prepared* p);
void unit(Prepared& p, bool restore, int* rc);
Rep rep(Prepared& p, int64_t n, bool gated);
void time_case(Held& h);
void free_case(Held& h);
double clock_now(uint64_t* throttle);
double read_rate(const uint8_t* src, int64_t bytes, int64_t copies, const void* ranges,
int ranges_n);
TimerOpts o_;
RadStream s_ = nullptr;
Phases* ph_ = nullptr;
std::vector<Held> held_;
int64_t held_bytes_ = 0;
int64_t next_id_ = 0;
std::map<int64_t, Timing> results_;
bool set_up_ = false, setup_failed_ = false;
std::string withheld_;
std::vector<std::string> header_;
int64_t footprint_ = 0; /* 0 in warm timing */
int64_t scale_ = 0; /* the footprint the probes and keep-alive are sized by */
RadEvent ev_[8] = {};
void* sweep_src_ = nullptr;
int64_t sweep_src_bytes_ = 0;
void* sweep_dst_ = nullptr;
int64_t sweep_bytes_ = 0, sweep_max_ = 0, sweep_off_ = 0;
void* word_ = nullptr; /* the launch floor's 256-byte target */
double floor_us_ = -1, floor_bracketed_us_ = -1;
std::string metrics_path_;
/* Throttler bits on at idle (some firmware keeps one set for good) and on after the warm-up's
* sustained load (a power limit that binds throughout): neither makes a batch worth repeating,
* since the next batch would see them too. */
uint64_t idle_throttle_ = 0, load_throttle_ = 0;
double warm_clock_ = -1;
std::chrono::steady_clock::time_point last_busy_{};
};
/* Times a host row on the calling thread: per-launch steady_clock times (or batches of launches
* past 200 us when nothing is restored), one untimed launch first unless the checked launch took a
* second or more, in-place operands restored outside the timed region, weights rotated over
* `footprint` bytes (0: warm). Stops at the median's 1% interval, the rep cap, or two seconds.
* Every operand the launch writes is a private copy, so the caller's buffers keep the checked
* launch's output. `checked_s` is that launch's wall time. */
Timing time_host(const TimedCase& c, const TimerOpts& o, int64_t footprint, double checked_s);
/* The bytes of the host's last-level caches, every distinct instance counted once (sysfs), or 0. */
int64_t host_llc_bytes();
} /* namespace kb */
} /* namespace rad */
+404 -188
View File
@@ -1,28 +1,25 @@
/* kfixture.cpp -- reading and writing the recorded reference. See kfixture.h for why it exists.
/* kfixture.cpp -- reading and writing the recorded reference (see kfixture.h).
*
* The format is binary and little-endian, because the payload is float samples and a text format
* for those is either lossy or three times the size. It is versioned in the header and a reader
* refuses a version it does not know rather than reading a struct that has moved -- the failure
* mode of getting that wrong is a report full of confident wrong numbers.
* Binary and little-endian, since the payload is float samples and text would be lossy or about
* 3x larger. Versioned; a reader refuses any version it does not know.
*/
#include "kfixture.h"
#include "opshapes.h"
#include "format/encoding.h"
#include "rad_plugin.h"
#include "rad_sample.h"
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <thread>
namespace rad {
namespace {
const char KF_MAGIC[4] = { 'R', 'K', 'B', '1' };
/* Every write goes through one of these and every read through its mirror, so a field added to
* one side and not the other is a compile error rather than a silent misparse. */
/* Primitive writer and its mirrored reader; save() and load() must stay field-for-field in step. */
struct W {
FILE* f;
bool ok = true;
@@ -52,8 +49,7 @@ struct R {
double f64() { double v = 0; raw(&v, 8); return v; }
std::string str() {
const uint32_t n = u32();
/* A length out of a corrupt file must not become an allocation. Nothing here is longer
* than an op name or a geometry key. */
/* Bound lengths read from a possibly corrupt file before allocating. */
if (!ok || n > (1u << 20)) { ok = false; return {}; }
std::string s(n, '\0');
raw(s.data(), n);
@@ -75,6 +71,40 @@ struct R {
}
};
/* The largest element count an operand may describe: past every real tensor (the largest is a
* 51.2 GB n-gram table, ~2^35 bf16 elements), well short of an overflow in any size product. */
constexpr int64_t KF_MAX_NUMEL = (int64_t)1 << 40;
/* Whether a loaded operand can describe a case (Kfixture::load). Absent operands carry nothing to
* check. */
bool operand_valid(const KfOperand& o) {
if (o.role < RAD_OPD_IN || o.role > RAD_OPD_WTAB) return false;
if (o.absent) return true;
if (rad_dtype_bits(o.dtype) <= 0) return false;
if (o.shape.empty() || o.shape.size() > (size_t)RAD_MAX_RANK) return false;
int64_t n = 1;
for (int64_t x : o.shape) {
if (x <= 0 || x > KF_MAX_NUMEL || n > KF_MAX_NUMEL / x) return false;
n *= x;
}
if (o.fill < KF_FILL_NORMAL || o.fill > KF_FILL_SAMPLE_PARAMS) return false;
if (o.idx_max < 0 || o.fill_chunk < 0 || o.idx_const < -1) return false;
if (o.has_enc) {
if (o.sel.empty() || o.sel.size() != o.sel_rows.size() ||
o.sel.size() != o.sel_cols.size())
return false;
for (size_t k = 0; k < o.sel.size(); ++k)
if (o.sel_rows[k] <= 0 || o.sel_cols[k] <= 0 || o.sel_rows[k] > KF_MAX_NUMEL ||
o.sel_cols[k] > KF_MAX_NUMEL / o.sel_rows[k])
return false;
}
if (o.have_ref) {
if (o.ref_n != n || o.ref_nonfinite < 0 || o.ref_nonfinite > n) return false;
if ((int64_t)o.sample.size() != std::min<int64_t>(n, KF_SAMPLES)) return false;
}
return true;
}
} /* namespace */
uint64_t kf_operand_seed(uint64_t case_seed, int k) {
@@ -85,9 +115,7 @@ uint64_t kf_operand_seed(uint64_t case_seed, int k) {
void kf_sample_positions(uint64_t seed, int64_t n, std::vector<int64_t>* out) {
out->clear();
if (n <= 0) return;
/* Small operands are sampled ENTIRELY rather than approximately: below the sample count there
* is nothing to gain by drawing, and an exhaustive check of a 256-element scale plane is
* strictly better than 1024 draws with repeats. */
/* Operands no larger than the sample count are sampled exhaustively. */
if (n <= KF_SAMPLES) {
out->reserve((size_t)n);
for (int64_t i = 0; i < n; ++i) out->push_back(i);
@@ -104,7 +132,7 @@ int Kfixture::save(const std::string& path) const {
if (!f) return RAD_E_IO;
W w{ f };
w.raw(KF_MAGIC, 4);
w.u32(version);
w.u32(KF_VERSION);
w.u32((uint32_t)KF_SAMPLES);
w.str(source);
w.str(oracle);
@@ -115,7 +143,6 @@ int Kfixture::save(const std::string& path) const {
w.u64(c.seed);
w.i64(c.m);
w.str(c.band);
w.u8(c.speed_only ? 1 : 0);
w.u32((uint32_t)c.params.size());
for (const KfParam& p : c.params) {
w.str(p.key);
@@ -131,7 +158,8 @@ int Kfixture::save(const std::string& path) const {
w.i64v(o.shape);
w.u8(o.absent ? 1 : 0);
w.u32((uint32_t)o.fill);
w.u8((uint8_t)((o.is_index ? 1 : 0) | (o.idx_unique ? 2 : 0) | (o.idx_cu ? 4 : 0)));
w.u8((uint8_t)((o.is_index ? 1 : 0) | (o.idx_unique ? 2 : 0) | (o.idx_cu ? 4 : 0) |
(o.idx_prefix ? 8 : 0) | (o.idx_history ? 16 : 0)));
w.i64(o.idx_max);
w.i64(o.idx_const);
w.i64(o.fill_chunk);
@@ -151,6 +179,8 @@ int Kfixture::save(const std::string& path) const {
w.f64(o.ref_sumsq);
w.i64(o.ref_nonfinite);
w.f32v(o.sample);
w.u32((uint32_t)o.sketch.size());
w.raw(o.sketch.data(), o.sketch.size() * sizeof(double));
}
}
}
@@ -168,13 +198,15 @@ int Kfixture::load(const std::string& path) {
if (!r.ok || std::memcmp(magic, KF_MAGIC, 4) != 0) { std::fclose(f); return RAD_E_FORMAT; }
version = r.u32();
const uint32_t samples = r.u32();
/* A file recorded with a different sample count is not readable as this one: the positions
* are DERIVED from the count, so every sample would be compared against the wrong element and
* the report would be a page of confident failures. */
if (version != 4 || samples != (uint32_t)KF_SAMPLES) {
/* Sample positions are derived from the count, so a file with a different count cannot be
* read. */
if (version < 4 || version > KF_VERSION || samples != (uint32_t)KF_SAMPLES) {
std::fclose(f);
return RAD_E_FORMAT;
}
const bool v4 = version == 4;
/* The sampler laws are version 6's; an older file naming one is corrupt. */
const bool sampler_laws = version >= 6;
source = r.str();
oracle = r.str();
recorded = r.str();
@@ -188,7 +220,7 @@ int Kfixture::load(const std::string& path) {
c.seed = r.u64();
c.m = r.i64();
c.band = r.str();
c.speed_only = r.u8() != 0;
if (v4) (void)r.u8(); /* a flag no recording set */
const uint32_t np = r.u32();
if (!r.ok || np > 256) { r.ok = false; break; }
for (uint32_t i = 0; i < np && r.ok; ++i) {
@@ -210,9 +242,14 @@ int Kfixture::load(const std::string& path) {
o.absent = r.u8() != 0;
o.fill = (int)r.u32();
const uint8_t flags = r.u8();
o.is_index = (flags & 1) != 0;
o.idx_unique = (flags & 2) != 0;
o.idx_cu = (flags & 4) != 0;
o.is_index = (flags & 1) != 0;
o.idx_unique = (flags & 2) != 0;
o.idx_cu = (flags & 4) != 0;
o.idx_prefix = (flags & 8) != 0;
o.idx_history = (flags & 16) != 0;
/* A flag this reader does not know is a law it would draw as another. */
if ((flags & ~0x1Fu) != 0) r.ok = false;
if (!sampler_laws && (o.idx_history || o.fill == KF_FILL_SAMPLE_PARAMS)) r.ok = false;
o.idx_max = r.i64();
o.idx_const = r.i64();
o.fill_chunk = r.i64();
@@ -238,7 +275,16 @@ int Kfixture::load(const std::string& path) {
o.ref_sumsq = r.f64();
o.ref_nonfinite = r.i64();
o.sample = r.f32v();
if (!v4) {
const uint32_t nk = r.u32();
if (!r.ok || (nk != 0 && nk != (uint32_t)KF_SKETCH)) { r.ok = false; break; }
o.sketch.resize(nk);
r.raw(o.sketch.data(), (size_t)nk * sizeof(double));
}
}
/* Version 4 drew no weight table: its references were computed on zeros. */
if (v4 && o.role == RAD_OPD_WTAB) o.undrawn = true;
if (r.ok && !operand_valid(o)) r.ok = false;
c.opd.push_back(std::move(o));
}
cases.push_back(std::move(c));
@@ -248,20 +294,11 @@ int Kfixture::load(const std::string& path) {
return ok ? RAD_OK : RAD_E_FORMAT;
}
} /* namespace rad */
namespace rad {
void kf_reduce(const float* v, int64_t n, uint64_t seed, double* sumsq, int64_t* nonfinite,
std::vector<float>* sample) {
/* THREADED, AND SUMMED IN BLOCK ORDER SO IT IS STILL DETERMINISTIC.
*
* This walks every element of every output of every case, which at a 248K-vocabulary
* logits_gemm is sixteen million elements and at gdn_recurrent_update rather more -- single
* threaded it dominates the CPU time of a replay that does almost no GPU work. Partial sums
* are accumulated per block and added back in block index order, so the answer does not depend
* on how many threads ran: a recorded sum of squares that moved with the core count would make
* every recorded reference machine-specific. */
/* Threaded (outputs reach tens of millions of elements, which would dominate a replay's CPU
* time). Per-block partial sums are added in block order, so the result does not depend on the
* thread count and recorded references are machine-independent. */
const int64_t nb = (n + KF_REDUCE_BLOCK - 1) / KF_REDUCE_BLOCK;
std::vector<double> part((size_t)std::max<int64_t>(nb, 1), 0.0);
std::vector<int64_t> partnf((size_t)std::max<int64_t>(nb, 1), 0);
@@ -277,18 +314,7 @@ void kf_reduce(const float* v, int64_t n, uint64_t seed, double* sumsq, int64_t*
part[(size_t)b] = ss;
partnf[(size_t)b] = nf;
};
if (nb <= 2) {
for (int64_t b = 0; b < nb; ++b) do_block(b);
} else {
unsigned hw = std::thread::hardware_concurrency();
if (hw == 0) hw = 1;
const int64_t nt = std::min<int64_t>(nb, (int64_t)hw);
std::vector<std::thread> th;
th.reserve((size_t)nt);
for (int64_t t = 0; t < nt; ++t)
th.emplace_back([&, t]() { for (int64_t b = t; b < nb; b += nt) do_block(b); });
for (auto& x : th) x.join();
}
rad_for_blocks(nb, do_block);
double ss = 0;
int64_t nf = 0;
for (int64_t b = 0; b < nb; ++b) { ss += part[(size_t)b]; nf += partnf[(size_t)b]; }
@@ -302,89 +328,267 @@ void kf_reduce(const float* v, int64_t n, uint64_t seed, double* sumsq, int64_t*
for (int64_t p : pos) sample->push_back(v[p]);
}
void kf_sketch(const float* v, int64_t n, uint64_t seed, std::vector<double>* out) {
out->assign(KF_SKETCH, 0.0);
if (n <= 0) return;
const int64_t nb = (n + KF_REDUCE_BLOCK - 1) / KF_REDUCE_BLOCK;
std::vector<double> part((size_t)nb * KF_SKETCH, 0.0);
const uint64_t key = seed ^ 0xD6E8FEB86659FD93ull;
rad_for_blocks(nb, [&](int64_t b) {
const int64_t lo = b * KF_REDUCE_BLOCK;
const int64_t hi = std::min<int64_t>(lo + KF_REDUCE_BLOCK, n);
double acc[KF_SKETCH] = {};
for (int64_t i = lo; i < hi; ++i) {
if (!std::isfinite(v[i])) continue;
/* Element i's signs: the low KF_SKETCH bits of a hash of (seed, i). Stateless, so a
* block needs nothing from the blocks before it. */
uint64_t z = key + (uint64_t)(i + 1) * 0x9E3779B97F4A7C15ull;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
z ^= z >> 31;
const double x = (double)v[i];
for (int j = 0; j < KF_SKETCH; ++j) acc[j] += ((z >> j) & 1u) ? -x : x;
}
for (int j = 0; j < KF_SKETCH; ++j) part[(size_t)b * KF_SKETCH + (size_t)j] = acc[j];
});
for (int64_t b = 0; b < nb; ++b)
for (int j = 0; j < KF_SKETCH; ++j)
(*out)[(size_t)j] += part[(size_t)b * KF_SKETCH + (size_t)j];
}
namespace {
/* A uniform in [0, 1) from 24 bits, as rad_sample_uniform01 forms one, and an integer in [0, n).
* Arithmetic only: a libm call could round differently on the machine that replays. */
float unit24(uint64_t& s) { return (float)(rad_splitmix(s) >> 40) * (1.0f / 16777216.0f); }
int64_t below(uint64_t& s, int64_t n) {
return n > 0 ? (int64_t)(rad_splitmix(s) % (uint64_t)n) : 0;
}
/* Row r's own stream, so a row's draw depends on neither the rows before it nor the row count. */
uint64_t row_stream(uint64_t seed, int64_t r) {
return seed ^ (0xD1B54A32D192ED03ull * (uint64_t)(r + 1));
}
/* RAD_FILL_SAMPLE_PARAMS: `rows` RadSampleParams, each what a request stages (core/sample/
* sampler.cpp), flags agreeing with fields. Row 0 switches every stage on, so a one-row case does
* work in each; on the others each stage is on in seven rows of eight and otherwise at its
* identity, so both paths of every stage run in a batch. One row in eight is greedy and one in
* sixteen a greedy request asking for logprobs, which the engine stages at top_k 1 without the
* flag.
*
* Every value is in the range a request uses, except XTC's threshold: candidates are drawn as
* normals, a flat distribution whose largest probability among 1024 is about 0.015, so llama.cpp's
* 0.1 would never find the two candidates above it that the stage needs. It is drawn in
* [1e-4, 1e-2), and below 1e-3 on row 0, where it must fire. The window lies inside the history
* plane (`fill_chunk` wide) and covers at least half of what follows its start; `mask_row` names a
* row of the bitmask plane (`idx_max` rows). DRY's penalty is its multiplier times
* base^(L - allowed) for a repeat of L tokens; the base stays below 2, so over the repeats the
* history law draws a penalty is a logit or two at the median and rarely past 10^3, and an error
* elsewhere in the plane is not lost in the norm of one huge value. */
void draw_sample_params(const KfOperand& d, uint64_t seed, int64_t rows, uint8_t* out) {
const int64_t hw = d.fill_chunk > 0 ? d.fill_chunk : 0;
const int64_t mask_rows = d.idx_max > 0 ? d.idx_max : 0;
/* What a positive last-n counts in when the op has no history plane: the engine's default. */
const int64_t span = hw > 0 ? hw : 64;
for (int64_t r = 0; r < rows; ++r) {
uint64_t s = row_stream(seed, r);
const bool all = r == 0;
auto u = [&] { return unit24(s); };
auto pick = [&](int64_t n) { return below(s, n); };
auto on = [&] { return all || pick(8) != 0; };
RadSampleParams p;
std::memset(&p, 0, sizeof p);
p.seed = rad_splitmix(s);
p.pos = (uint64_t)pick(4096);
const int64_t kind = all ? 15 : pick(16);
const bool greedy = kind < 2, top1 = kind == 2;
/* [0.5, 1) or (1, 1.5]: 1 is the identity, drawn on its own. */
const float t = u();
p.temp = greedy || top1 ? 0.0f : on() ? (t < 0.5f ? 0.5f + t : 2.0f - t) : 1.0f;
p.top_k = top1 ? 1 : on() ? (int32_t)(20 + pick(81)) : 0;
p.top_p = on() ? 0.8f + 0.19f * u() : 1.0f;
p.min_p = on() ? 0.01f + 0.09f * u() : 0.0f;
p.typical_p = on() ? 0.7f + 0.29f * u() : 1.0f;
/* Penalties: each of the three at its identity in one row of four, never all three. */
const bool pen = on();
p.rep_penalty = 1.0f;
p.penalty_last_n = 64;
if (pen) {
if (all || pick(4)) p.rep_penalty = 1.0f + 0.3f * (1.0f - u());
if (all || pick(4)) p.freq_penalty = 0.5f * (1.0f - u());
if (all || pick(4)) p.pres_penalty = 0.5f * (1.0f - u());
if (p.rep_penalty == 1.0f && p.freq_penalty == 0.0f && p.pres_penalty == 0.0f)
p.rep_penalty = 1.1f;
const int64_t w = all ? 0 : pick(3);
p.penalty_last_n = w == 0 ? -1 : w == 1 ? 64 : (int32_t)(1 + pick(span));
p.flags |= RAD_SP_PENALTY;
} else if (pick(2)) {
p.penalty_last_n = 0;
}
/* DRY. On one row in four a breaker in the window caps the repeat, at no less than the
* allowed length (the host turns DRY off below it). */
const bool dry = on();
p.dry_base = 1.75f;
p.dry_allowed_length = 2;
p.dry_penalty_last_n = -1;
if (dry) {
p.dry_multiplier = 0.25f + 0.75f * u();
p.dry_base = 1.5f + 0.5f * u();
if (!all && pick(4) == 0) p.dry_allowed_length = (int32_t)(1 + pick(3));
if (!all && pick(2))
p.dry_penalty_last_n = (int32_t)(8 + pick(span > 8 ? span - 7 : 1));
if (!all && pick(4) == 0) p.dry_rep_limit = p.dry_allowed_length + (int32_t)pick(7);
p.flags |= RAD_SP_DRY;
}
/* XTC's coin comes up in about seven rows of eight that set it. */
p.xtc_threshold = 0.1f;
if (on()) {
p.xtc_probability = all ? 1.0f : 0.75f + 0.25f * u();
p.xtc_threshold = (all || pick(2) ? 1e-4f : 1e-3f) * (1.0f + 9.0f * u());
p.flags |= RAD_SP_XTC;
}
/* The engine's window runs to the newest token at the plane's end; half the windows do,
* the rest end earlier. */
if (hw > 0 && (pen || dry)) {
const int64_t off = all || pick(2) ? 0 : pick(hw / 2 + 1);
const int64_t rem = hw - off;
p.hist_off = (int32_t)off;
p.hist_len = (int32_t)(all || pick(2) ? rem : (rem + 1) / 2 + pick(rem / 2 + 1));
}
p.mask_row = -1;
if (mask_rows > 0 && on()) {
p.mask_row = (int32_t)pick(mask_rows);
p.flags |= RAD_SP_MASK;
}
if (greedy) p.flags |= RAD_SP_GREEDY;
if (top1 || (!greedy && on())) p.flags |= RAD_SP_LOGPROBS;
std::memcpy(out + (size_t)r * sizeof p, &p, sizeof p);
}
}
/* RAD_OPD_F_IDX_HISTORY: `rows` rows of `w` ids in [0, range), each text that repeats itself. A row
* draws on 16 ids spread over the range, in runs of one to three, and four times in five copies 3
* to 12 of its own earlier tokens. A fresh id follows every copy, so a repeat is rarely much longer
* than the copy that made it, which keeps DRY's exponent small; a window ending inside a 64-token
* row ends inside a repeat about three times in four. The row closes in a loop, its last 2 to 4
* tokens repeated three more times, so a window reaching its end always ends in a repeat, and one
* that DRY finds at three earlier positions. */
void draw_history(int64_t rows, int64_t w, int64_t range, uint64_t seed, float* v) {
for (int64_t r = 0; r < rows; ++r) {
uint64_t s = row_stream(seed, r);
int64_t ids[16];
for (int64_t& x : ids) x = below(s, range);
float* row = v + r * w;
int64_t i = 0;
while (i < w) {
if (i >= 4 && below(s, 5) < 4) {
const int64_t src = below(s, i - 2), len = 3 + below(s, 10);
for (int64_t t = 0; t < len && i < w; ++t, ++i) row[i] = row[src + t];
if (i < w) row[i++] = (float)ids[below(s, 16)];
} else {
const int64_t len = 1 + below(s, 3);
for (int64_t t = 0; t < len && i < w; ++t, ++i) row[i] = (float)ids[below(s, 16)];
}
}
const int64_t p = 2 + below(s, 3);
if (w >= 8 * p)
for (int64_t j = w - 3 * p; j < w; ++j) row[j] = row[j - p];
}
}
} /* namespace */
void kf_draw(const std::vector<KfOperand>& opd, size_t k, int64_t M, int64_t vocab_rows,
uint64_t seed, std::vector<uint8_t>* out) {
const KfOperand& d = opd[k];
int64_t n = 1;
for (int64_t x : d.shape) n *= x;
out->assign((size_t)rad_dtype_bytes(d.dtype, n), 0);
if (n <= 0 || d.absent) return;
if (d.role != RAD_OPD_IN && d.role != RAD_OPD_INOUT && d.role != RAD_OPD_WEIGHT) return;
if (n <= 0 || d.absent || out->empty()) return; /* empty: a dtype the core cannot size */
if (d.role != RAD_OPD_IN && d.role != RAD_OPD_INOUT && d.role != RAD_OPD_WEIGHT &&
d.role != RAD_OPD_WTAB)
return;
if (d.undrawn) return;
const bool weightish = d.role == RAD_OPD_WEIGHT || d.role == RAD_OPD_WTAB;
if (d.role == RAD_OPD_WTAB && d.has_enc) {
std::string why;
if (kf_draw_table(d, k, out, &why) != RAD_OK) out->assign(out->size(), 0);
return;
}
/* A WEIGHT'S CONTENT DOES NOT DEPEND ON THE BATCH SIZE, so its seed must not either.
*
* The M sweep runs the same GEMM at eight or ten query lengths. Under a per-case seed each of
* those points would re-draw the same 178-million-element weight from scratch -- ten
* Box-Muller passes over 178M elements for one (N, K), which dominates a replay's wall clock.
* Deriving the seed from the operand's own identity instead -- its position, dtype and extents
* -- makes every point of the sweep ask for the SAME bytes, which a caller can then draw once
* and keep. kf_weight_seed is public for exactly that: it is the cache key.
*
* It costs nothing in coverage. Which pseudorandom weight a kernel is checked against was
* never the point; that two implementations agree about it is. */
if (d.role == RAD_OPD_WEIGHT) seed = kf_weight_seed(d, k);
/* A weight's seed comes from its own identity (position, dtype, extents), not the case, so
* every point of an M sweep uses the same bytes and the caller can draw them once
* (kf_weight_seed is the cache key). */
if (weightish) seed = kf_weight_seed(d, k);
/* Sampler rows are structs, written whole; a row that does not fit is left zero. */
if (!weightish && !d.is_index && d.fill == KF_FILL_SAMPLE_PARAMS) {
draw_sample_params(d, seed, (int64_t)(out->size() / sizeof(RadSampleParams)), out->data());
return;
}
std::vector<float> tmp;
/* A BIG OPERAND IS DRAWN IN BLOCKS AND NEVER MATERIALISES AS FLOATS.
/* Large plain-normal operands (every weight and ordinary activation) are drawn block by block,
* each block on its own thread and narrowed into its own byte range, avoiding a full-size
* float intermediate (713 MB for one fp8 GEMM weight). The bytes do not depend on the thread
* count: the stream is seeded per RAD_FILL_BLOCK block, and every dtype the draw narrows to
* packs whole elements into a byte. The shaped fills below read across the whole tensor and
* are small, so they are not blocked.
*
* The plain-normal path -- which is every weight and every ordinary activation, so almost all
* of the bytes here -- would otherwise allocate one float vector the size of the whole tensor
* and narrow it in one pass. At an fp8 GEMM weight that is 713 MB of scratch to produce 178 MB
* of fp8, touched twice, for one case. In blocks it is a few hundred kilobytes that stays in
* cache, and the result is identical because rad_fill_normal is block-seeded at exactly this
* width.
*
* Only this path blocks. The shaped fills below (a triangular inverse, a chunk-local cumulative
* sum) read across the whole tensor by construction and are small by construction, so blocking
* them would buy nothing and get the shapes wrong. */
/* A WEIGHT CAN BE AN INDEX, so `role == WEIGHT` is not the whole answer here. An operand whose
* VALUES are sizes or offsets -- a weight by role, an index by content -- must not be drawn as
* standard normals cast to its integer dtype, which is zeros and negatives. ngram_ids is the
* case: it refuses `vocab_size <= 0` and `offset < 0` by name, so drawing it as a plain weight
* makes the ORACLE refuse every geometry and the op is never checked on any plugin. That
* refusal reads exactly like a shape the reference does not serve, so it is easy to miss.
*
* The index path runs values through the float `tmp` below, so an index constant past 2^24
* does not survive the round trip -- fine for a vocabulary and not for a token id at a 250k
* vocab, which is why the constant here is the vocabulary and not the id. */
const bool plain = (d.role == RAD_OPD_WEIGHT && !d.is_index) ||
(!d.is_index && d.fill == KF_FILL_NORMAL);
if (plain && n > RAD_FILL_BLOCK && rad_dtype_bytes(d.dtype, 1) >= 1) {
const float sigma = d.role == RAD_OPD_WEIGHT ? 0.02f : 1.0f;
tmp.resize((size_t)RAD_FILL_BLOCK);
for (int64_t lo = 0; lo < n; lo += RAD_FILL_BLOCK) {
* A weight-role operand may hold indices (e.g. ngram_ids sizes and offsets, which the oracle
* refuses when <= 0 or negative), so it is drawn as an index, not as normals. Index values
* pass through the float `tmp`, exact only up to 2^24. */
const bool plain = (weightish && !d.is_index) || (!d.is_index && d.fill == KF_FILL_NORMAL);
if (plain) {
/* Sigma 0.02 matches real checkpoint weights; unit variance would put an fp8 quantiser's
* amax far from where it sits on real data. */
const float sigma = weightish ? 0.02f : 1.0f;
const int64_t nb = (n + RAD_FILL_BLOCK - 1) / RAD_FILL_BLOCK;
uint8_t* dst = out->data();
rad_for_blocks(nb, [&](int64_t b) {
thread_local std::vector<float> blk;
const int64_t lo = b * RAD_FILL_BLOCK;
const int64_t len = std::min<int64_t>(RAD_FILL_BLOCK, n - lo);
rad_fill_normal_block(tmp.data(), len, seed, lo / RAD_FILL_BLOCK, sigma);
rad_narrow(tmp.data(), d.dtype, len,
out->data() + rad_dtype_bytes(d.dtype, lo));
}
blk.resize((size_t)len);
rad_fill_normal_block(blk.data(), len, seed, b, sigma);
rad_narrow(blk.data(), d.dtype, len, dst + rad_dtype_bytes(d.dtype, lo));
});
return;
}
tmp.assign((size_t)n, 0.0f);
if (d.role == RAD_OPD_WEIGHT && !d.is_index) {
/* A WEIGHT IS A SMALL DRAW, and the 0.02 sigma is not cosmetic: a checkpoint's weights
* are that size, and drawing them at unit variance puts an fp8 quantiser's amax three
* orders of magnitude off where a real one sits, so the case would measure the
* quantiser's behaviour on data no model produces. */
rad_fill_normal(tmp.data(), n, seed, 0.02f);
rad_narrow(tmp.data(), d.dtype, n, out->data());
return;
}
if (d.is_index && d.idx_cu) {
/* Cumulative sequence lengths, [0 .. T]: the batch's shape, not a draw. Every GDN kernel
* opens by reading cu[n] before any null test, so a wrong one is a fault and not a wrong
* answer. */
if (d.is_index && d.idx_prefix) {
/* A routing histogram's offsets [0, ..., T]: non-decreasing, first 0 and last T, so each
* of the n - 1 buckets holds a valid run. T is idx_max - 1 (idx_max bounds a value
* exclusively). The runs come from T uniform choices of a bucket. */
const int64_t buckets = n > 1 ? n - 1 : 1;
const int64_t T = d.idx_max > 0 ? d.idx_max - 1 : 0;
std::vector<int64_t> cnt((size_t)buckets, 0);
uint64_t s2 = seed;
for (int64_t t = 0; t < T; ++t) ++cnt[(size_t)(rad_splitmix(s2) % (uint64_t)buckets)];
int64_t acc = 0;
for (int64_t i = 1; i < n; ++i) {
acc += cnt[(size_t)(i - 1)];
tmp[(size_t)i] = (float)acc;
}
} else if (d.is_index && d.idx_cu) {
/* Cumulative sequence lengths [0 .. T]. GDN kernels read cu[n] before any null test, so
* a wrong one faults. */
const int64_t S = n > 1 ? n - 1 : 1;
for (int64_t i = 0; i < n; ++i) tmp[(size_t)i] = (float)((i * M) / S);
} else if (d.is_index && d.idx_const >= 0) {
/* A length, not a choice. `seqused` is the case: a random context shorter than the query
* makes causal attention read a prefix that does not exist, and both implementations
* agree about the garbage. */
/* A fixed length (see OpdShape::idx_const). */
for (int64_t i = 0; i < n; ++i) tmp[(size_t)i] = (float)d.idx_const;
} else if (d.is_index && d.idx_unique) {
/* A scatter's destinations, distinct: a partial Fisher-Yates over the range. Two tokens
* on one slot is a race the two implementations resolve differently, so the comparison
* would measure the scheduler. */
/* Distinct scatter destinations (see OpdShape::idx_unique): partial Fisher-Yates. */
uint64_t s2 = seed;
const int64_t range = d.idx_max > 0 ? d.idx_max : n;
std::vector<int32_t> pool((size_t)range);
@@ -396,38 +600,33 @@ void kf_draw(const std::vector<KfOperand>& opd, size_t k, int64_t M, int64_t voc
}
for (int64_t i = range; i < n; ++i) tmp[(size_t)i] = -1.0f;
} else if (d.is_index) {
/* An index operand indexes the operand before it, whose leading extent is the only legal
* range -- unless the recipe named the range itself, which the paged pair has to: a KV
* slot indexes n_blocks * block_size and a block-table entry indexes n_blocks, and neither
* is any operand's dim 0. */
uint64_t s2 = seed;
/* Range: idx_max if the recipe set it, else the previous operand's leading extent, else
* vocab_rows. */
int64_t rows = vocab_rows > 0 ? vocab_rows : 32000;
if (k > 0 && !opd[k - 1].shape.empty()) rows = opd[k - 1].shape[0];
if (d.idx_max > 0) rows = d.idx_max;
if (rows <= 0) rows = 1;
for (int64_t i = 0; i < n; ++i)
tmp[(size_t)i] = (float)(rad_splitmix(s2) % (uint64_t)rows);
if (d.idx_history) {
const int64_t w = d.shape.empty() ? n : d.shape.back();
draw_history(n / w, w, rows, seed, tmp.data());
} else {
uint64_t s2 = seed;
for (int64_t i = 0; i < n; ++i)
tmp[(size_t)i] = (float)(rad_splitmix(s2) % (uint64_t)rows);
}
} else {
rad_fill_normal(tmp.data(), n, seed, 1.0f);
/* INTO THE OPERAND'S DOMAIN, where a normal draw is outside it. */
/* Map into the operand's domain where normals fall outside it. The maps run in double and
* round once, as the normals do: glibc's float routines differ between releases, and a
* fixture recorded on one host is replayed on another against its exact answers. */
if (d.fill == KF_FILL_SIGMOID) {
for (int64_t i = 0; i < n; ++i) tmp[(size_t)i] = 1.0f / (1.0f + std::exp(-tmp[(size_t)i]));
for (int64_t i = 0; i < n; ++i)
tmp[(size_t)i] = (float)(1.0 / (1.0 + std::exp(-(double)tmp[(size_t)i])));
} else if (d.fill == KF_FILL_TRI_LOWER) {
/* UNIT DIAGONAL, SMALL OFF-DIAGONAL, and the diagonal is the whole point.
*
* `A` is the chunked delta rule's intra-chunk matrix -- I + tril(diag(beta) K K^T, -1)
* -- so it is UNIT lower triangular by construction and its inverse is bounded. Drawn
* with a normal on the diagonal it is not: a diagonal element near zero makes the
* inverse enormous, and `gdn_kkt_solve` then returns values of order 1e20 with a
* rel_l2 that grows with the chunk count. Two implementations summing an
* ill-conditioned product in different orders disagree by however ill-conditioned it
* is, so that number is the CONDITION NUMBER OF THE TEST, not an error in the kernel.
*
* This is the same correction FillSigmoid and FillGateCumsum already are: put the
* operand inside the domain the op is only ever handed, or the comparison measures
* the harness. The strictly-upper part stays zeroed -- whether it is read at all is a
* convention the two implementations never disagree about on a real matrix, because
* the same library's kkt_solve produced it. */
/* Unit diagonal, small off-diagonal, upper part zero. `A` is the chunked delta rule's
* I + tril(diag(beta) K K^T, -1), unit lower triangular with a bounded inverse. A
* normal diagonal would make it ill-conditioned (gdn_kkt_solve outputs ~1e20), and the
* comparison would measure the condition number, not the kernel. */
const int64_t ch = d.fill_chunk > 0 ? d.fill_chunk : 1;
const int64_t heads = d.shape.size() >= 3 ? d.shape[1] : 1;
const int64_t rows = (heads * ch) != 0 ? n / (heads * ch) : n;
@@ -441,9 +640,8 @@ void kf_draw(const std::vector<KfOperand>& opd, size_t k, int64_t M, int64_t voc
else tmp[i] *= 0.25f;
}
} else if (d.fill == KF_FILL_GATE_CUMSUM) {
/* Rows are [tokens, heads] and the cumsum runs down TOKENS within a chunk, resetting
* at each boundary -- which is what chunk_local_cumsum produces and what the scan
* assumes. */
/* Rows are [tokens, heads]; the cumsum runs down tokens and resets at each chunk
* boundary, as chunk_local_cumsum produces. */
const int64_t heads = d.shape.size() >= 2 ? d.shape.back() : 1;
const int64_t rows = heads > 0 ? n / heads : n;
const int64_t ch = d.fill_chunk > 0 ? d.fill_chunk : rows;
@@ -451,17 +649,14 @@ void kf_draw(const std::vector<KfOperand>& opd, size_t k, int64_t M, int64_t voc
float acc = 0.0f;
for (int64_t t = 0; t < rows; ++t) {
if (t % ch == 0) acc = 0.0f;
acc -= std::log1p(std::exp(tmp[(size_t)(t * heads + h)]));
acc -= (float)std::log1p(std::exp((double)tmp[(size_t)(t * heads + h)]));
tmp[(size_t)(t * heads + h)] = acc;
}
}
} else if (d.fill == KF_FILL_UNIT_ROW) {
/* UNIT L2 NORM ALONG THE LAST DIMENSION, which is what the model's own qk_norm hands
* the gated-delta-net path. Drawn as plain normals over a 128-wide head the key has
* norm ~11, the solve's matrix I + tril(beta k k^T, -1) then has off-diagonals two
* orders of magnitude too large, and its inverse is astronomical -- gdn_kkt_solve
* returns values of order 1e18 and a rel_l2 that moves with the draw. That is not a
* defect in the kernel; it is an input outside the domain the op is ever handed. */
/* Unit L2 norm along the last dimension, as the model's qk_norm provides. Plain normals
* over a 128-wide head have norm ~11, making the solve ill-conditioned (outputs
* ~1e18). */
const int64_t w = d.shape.empty() ? n : d.shape.back();
if (w > 0) {
for (int64_t r = 0; r + w <= n; r += w) {
@@ -477,20 +672,47 @@ void kf_draw(const std::vector<KfOperand>& opd, size_t k, int64_t M, int64_t voc
rad_narrow(tmp.data(), d.dtype, n, out->data());
}
} /* namespace rad */
namespace rad {
uint64_t kf_weight_seed(const KfOperand& d, size_t k) {
uint64_t s = 0x9E3779B97F4A7C15ull ^ (uint64_t)(k + 1) ^ ((uint64_t)d.dtype << 17);
for (int64_t x : d.shape) { s ^= (uint64_t)x; s = rad_splitmix(s); }
return rad_splitmix(s);
}
} /* namespace rad */
namespace rad {
int kf_draw_table(const KfOperand& d, size_t k, std::vector<uint8_t>* out, std::string* why) {
out->clear();
if (!d.has_enc || d.shape.size() < 2 || d.shape[0] <= 0) {
if (why) *why = "a weight table needs an encoding and a leading expert dimension";
return RAD_E_SHAPE;
}
const int64_t ne = d.shape[0];
/* One expert: the table's selection over its shape without the leading dimension. */
KfOperand one = d;
one.role = RAD_OPD_WEIGHT;
one.shape.assign(d.shape.begin() + 1, d.shape.end());
const int64_t per = rad_dtype_bytes(d.dtype, rad_numel(one.shape));
if (per <= 0) {
if (why) *why = "a dtype the core cannot size";
return RAD_E_DTYPE;
}
out->assign((size_t)(per * ne), 0);
const uint64_t base = kf_weight_seed(d, k);
std::vector<std::vector<uint8_t>> pl;
std::vector<uint8_t> logical;
for (int64_t e = 0; e < ne; ++e) {
uint64_t es = base ^ (0xC2B2AE3D27D4EB4Full * (uint64_t)(e + 1));
kf_draw_planes(one, rad_splitmix(es), &pl);
std::string w;
const int rc = kf_planes_logical(one, pl, &logical, &w);
if (rc != RAD_OK || (int64_t)logical.size() != per) {
if (why) *why = rc != RAD_OK ? w : "an expert decodes to a different size than the "
"table holds";
out->assign((size_t)(per * ne), 0);
return rc != RAD_OK ? rc : RAD_E_SHAPE;
}
std::memcpy(out->data() + per * e, logical.data(), (size_t)per);
}
return RAD_OK;
}
void kf_operand_enc(const WeightInfo& w, KfOperand* d) {
d->has_enc = true;
@@ -515,7 +737,7 @@ void draw_plane(const RadEncoding& e, const RadEncPlane& p, int64_t rows, int64_
const int64_t n = rows * cols;
uint64_t s = seed;
if (!std::strcmp(p.role, "t.perm")) {
/* a permutation of the columns, each row its own: Fisher-Yates over the identity */
/* a per-row permutation of the columns: Fisher-Yates over the identity */
for (int64_t r = 0; r < rows; ++r) {
std::vector<int64_t> v((size_t)cols);
for (int64_t j = 0; j < cols; ++j) v[(size_t)j] = j;
@@ -531,10 +753,13 @@ void draw_plane(const RadEncoding& e, const RadEncPlane& p, int64_t rows, int64_
const bool ints = pb || p.dtype == RAD_I8 || p.dtype == RAD_U8 || p.dtype == RAD_I16 ||
p.dtype == RAD_U16 || p.dtype == RAD_I32 || p.dtype == RAD_U32;
const bool codes = !std::strcmp(p.role, "codes");
if (ints || p.dtype == RAD_FP4E2M1 || p.dtype == RAD_FP6E2M3 || p.dtype == RAD_FP6E3M2) {
/* EVERY BIT PATTERN OF THESE IS A VALUE, so a uniform draw over the patterns is the
* widest test -- except a code into a codebook, which is held inside it, and a wide
* integer, which a reference would sum past f32's exact range. */
const bool minifloat = p.dtype == RAD_FP4E2M1 || p.dtype == RAD_FP6E2M3 ||
p.dtype == RAD_FP6E3M2;
if (ints || minifloat) {
/* Every bit pattern is a value, so draw uniformly over patterns, except codebook codes
* (kept inside the codebook) and wide integers (capped at 12 bits so a reference's sums
* stay exact in f32). The sub-byte floats have no infinity or NaN, so their patterns are
* stored as drawn: rad_store_f32 does not encode them. */
const int bits = rad_dtype_bits(p.dtype);
uint64_t range = bits >= 16 ? 1u << 12 : 1ull << bits;
const int64_t entries = codes ? codebook_entries(e) : 0;
@@ -542,7 +767,7 @@ void draw_plane(const RadEncoding& e, const RadEncPlane& p, int64_t rows, int64_
for (int64_t r = 0; r < rows; ++r)
for (int64_t j = 0; j < cols; ++j) {
uint32_t c = (uint32_t)(rad_splitmix(s) % range);
if (pb) { rad_store_bits(out + r * rb, pb, j, c); continue; }
if (pb || minifloat) { rad_store_bits(out + r * rb, bits, j, c); continue; }
const bool neg = (p.dtype == RAD_I8 || p.dtype == RAD_I16 || p.dtype == RAD_I32);
const float v = neg ? (float)((int64_t)c - (int64_t)(range / 2)) : (float)c;
rad_store_f32(out + r * rb, p.dtype, j, v);
@@ -550,23 +775,27 @@ void draw_plane(const RadEncoding& e, const RadEncPlane& p, int64_t rows, int64_
return;
}
if (p.dtype == RAD_E8M0) {
/* 2^-4 .. 2^4: a block scale, which a draw over every exponent would make an overflow */
/* 2^-4 .. 2^4; a draw over every exponent would overflow */
for (int64_t r = 0; r < rows; ++r)
for (int64_t j = 0; j < cols; ++j)
out[r * rb + j] = (uint8_t)(123 + rad_splitmix(s) % 9);
return;
}
/* A float plane: a normal draw, and a magnitude for what scales (a scale or a minimum is
* read as one, and a negative one is a sign flip no quantiser writes). */
/* Float plane: normal draw; scale planes get a positive magnitude, since no quantiser writes a
* negative scale. Rows are stored independently, so they go to threads in chunks. */
std::vector<float> f((size_t)n);
rad_fill_normal(f.data(), n, seed, 1.0f);
const bool mag = rad_enc_role_in_chain(p.role, "scale") || !std::strcmp(p.role, "t.scale");
for (int64_t r = 0; r < rows; ++r)
for (int64_t j = 0; j < cols; ++j) {
float v = f[(size_t)(r * cols + j)];
if (mag) v = 0.25f + std::fabs(v);
rad_store_f32(out + r * rb, p.dtype, j, v);
}
const int64_t chunk = std::max<int64_t>(1, RAD_FILL_BLOCK / std::max<int64_t>(cols, 1));
rad_for_blocks((rows + chunk - 1) / chunk, [&](int64_t b) {
const int64_t r1 = std::min<int64_t>(rows, (b + 1) * chunk);
for (int64_t r = b * chunk; r < r1; ++r)
for (int64_t j = 0; j < cols; ++j) {
float v = f[(size_t)(r * cols + j)];
if (mag) v = 0.25f + std::fabs(v);
rad_store_f32(out + r * rb, p.dtype, j, v);
}
});
}
} /* namespace */
@@ -613,17 +842,13 @@ int kf_lay_weight(const RadKernelInfo* info, const RadParam* p, int n_p, int ope
*lay = RadLayout{};
const int rc = info->layout(p, n_p, operand, &d.enc, d.sel.data(), pt, n, lay);
if (rc != RAD_OK) return rc;
/* A layout with no relayout behind it is a row that would fail at load; said so here rather
* than handed on as bytes nobody wrote. */
/* A layout without a relayout would fail at load; report it rather than return unwritten
* bytes. */
if (lay->bytes <= 0 || !info->relayout) return RAD_E_STATE;
out->assign((size_t)lay->bytes, 0);
return info->relayout(p, n_p, operand, &d.enc, d.sel.data(), pt, n, out->data(), lay->bytes);
}
} /* namespace rad */
namespace rad {
int64_t kf_vocab_rows(const std::vector<KfOperand>& opd) {
int64_t v = 0;
for (const KfOperand& d : opd)
@@ -631,19 +856,10 @@ int64_t kf_vocab_rows(const std::vector<KfOperand>& opd) {
return v;
}
} /* namespace rad */
namespace rad {
/* HOW THE ENGINE DESCRIBES A RE-LAID WEIGHT, AND THEREFORE HOW THIS TOOL MUST.
*
* STORED DTYPE, DECLARED SHAPE -- which is what Ctx::refresh_weights does, and not what the
* RadLayout says. The two differ for any layout that changes the width: libr4d's fp8 lm_head
* appends each row's 128-block scales to its own row, so the stored plane is [N, K + 2*sk] while
* the operand the kernel is handed is still [N, K] of E4M3 and the kernel finds the scales past
* the end of its own row. Described by the stored shape instead, the kernel reads K = K + 2*sk,
* finds it is not the K it was compiled for, and refuses the geometry it was selected for.
*
* Describing the operand any other way here would be testing a call the engine never makes. */
/* Describe a re-laid weight as Ctx::refresh_weights does: stored dtype, declared shape, not the
* RadLayout's shape. They differ when a layout changes the width: libr4d's fp8 lm_head appends each
* row's 128-block scales, storing [N, K + 2*sk], while the kernel is still handed [N, K] of E4M3
* and finds the scales past the end of the row. */
void kf_describe_laid(const KfOperand& d, const RadLayout& lay, void* data, RadTensor* out) {
*out = RadTensor{};
out->data = data;
+110 -112
View File
@@ -1,39 +1,23 @@
/* kfixture.h -- the recorded reference a kernel library is checked against, with no model in the
* room.
/* kfixture.h -- a recorded reference to check kernel libraries against without a model.
*
* WHY THIS EXISTS. Checking against a real container -- declare the model's graph, take the
* weights out of the .rad in the layout the resolved kernel asked for, run the oracle beside the
* kernel and compare -- is the right test of a CONTAINER and the wrong test of a LIBRARY. It needs
* a 27B file nobody has on a build machine, and it spends its whole runtime inside libref, which
* is a straight-loop host implementation: at model shapes a single `logits_gemm` over a 248K
* vocabulary costs seconds of wall clock and a single fp8 GEMM tens of seconds, so a full pass
* runs for tens of minutes to produce numbers that do not change between runs.
* Checking against a real container needs a 27B model file and runs libref (straight host loops)
* at model shapes, which takes tens of minutes. Instead the oracle runs once when a fixture is
* recorded, and the result is checked in. Libraries are then checked in seconds on any machine,
* and the fixture doubles as a regression test of libref itself (a live comparison would move
* both sides together).
*
* So the oracle runs ONCE, when a fixture is recorded, and what it produced is checked in. A
* library is then checked against a fixed artifact in seconds, on any machine, with no model
* present -- and the artifact is a regression test on libref itself, which a live oracle can never
* be: if ref's arithmetic drifts, a live comparison moves both sides together and reports
* agreement.
* Full outputs at model shapes would be tens of gigabytes, so per output operand it stores:
*
* WHAT IS RECORDED, AND WHY IT IS NOT THE WHOLE OUTPUT. A recorded reference for every case at
* real model shapes is tens of gigabytes -- one `logits_gemm` output alone is 31 MB -- and a
* repository is not the place for it. What is stored instead, per output operand:
* - the sum of squares over every element, and the count: the rel_l2 denominator, and the check
* a sample cannot make (a correct first tile followed by zeros);
* - the number of non-finite elements (a NaN against a number is a failure, checked first);
* - the values at KF_SAMPLES seed-derived positions. 1024 samples catch an error rate of 1e-3
* with probability 64% and 1e-2 with probability > 1 - 3e-5;
* - from version 5, KF_SKETCH seeded random-sign projections of the whole output. Their
* difference estimates the full-tensor rel_l2 to about +-25%, so a localised error the samples
* miss and the norm cannot see (one permuted or sign-flipped tile of a large output) fails.
*
* - the sum of squares over EVERY element, and the element count. This is the rel_l2
* denominator and it is also the check a sample cannot make: a kernel that writes a correct
* first tile and zeros the rest has the right values everywhere the sample looks and the
* wrong norm.
* - how many elements were non-finite. Not a tolerance question (spec: a NaN on one side and a
* number on the other is a failure, checked first).
* - the value at N sampled positions, the positions derived from a seed so only the values are
* stored. 1024 of them: a kernel wrong in one element per thousand is caught with probability
* 1 - (1 - 1e-3)^1024 = 64%, one wrong in a hundred with probability better than 1 - 3e-5, and
* a kernel wrong in one element out of seventeen million is beneath what an rel_l2 over
* seventeen million elements would have reported anyway.
*
* INPUTS ARE NOT STORED AT ALL. They are drawn from a seed that IS stored, by the same code on
* both sides, so the bytes are identical without anyone shipping them. That is also what keeps
* the file small enough to read at every ctest run.
* Inputs are not stored: both sides draw them from the stored seed with the same code.
*/
#pragma once
#include "rad_core.h"
@@ -44,29 +28,35 @@
namespace rad {
/* How many positions of each output operand are sampled. Fixed rather than a parameter: it is
* baked into every recorded file, and a file whose sample count differs from the reader's is a
* file the reader would silently misinterpret. */
/* Positions sampled per output operand. Fixed because it is baked into every recorded file. */
constexpr int KF_SAMPLES = 1024;
/* The block the full-tensor reduction is threaded over. Part of the contract for the same reason
* RAD_FILL_BLOCK is: the partial sums are added back in block order, so the answer is the same
* however many threads ran, and a reference recorded on one machine reads on another. */
/* Block size of the threaded full-tensor reduction. Part of the contract, like RAD_FILL_BLOCK:
* partial sums are combined in block order, so the result is independent of thread count. */
constexpr int64_t KF_REDUCE_BLOCK = 1 << 18;
/* The fill laws, mirroring OpdShape::Fill. Named here rather than shared with it because the
* fixture is the on-disk contract: OpdShape is free to renumber, this is not. */
/* Projections per output in a version-5 recording. 32 gives the rel_l2 estimate a relative spread
* of sqrt(2/32), about 25%. Fixed because it is baked into every recorded file. */
constexpr int KF_SKETCH = 32;
/* The format version this tree writes. Versions 4 and 5 still load: version 4 lacks the sketch, the
* prefix fill law and drawn weight tables (KfOperand::undrawn), version 5 the sampler laws (the
* request-row fill and the token history). */
constexpr uint32_t KF_VERSION = 6;
/* The fill laws, mirroring OpdShape::Fill. Separate because these values are on disk and must not
* be renumbered. */
enum {
KF_FILL_NORMAL = 0,
KF_FILL_SIGMOID = 1,
KF_FILL_GATE_CUMSUM = 2,
KF_FILL_TRI_LOWER = 3,
KF_FILL_UNIT_ROW = 4,
KF_FILL_SAMPLE_PARAMS = 5,
};
/* A geometry key/value, stored TYPED. The alternative is to store `Geometry::str()` and parse it
* back, and there is no parser -- writing one means deciding whether `1e+07` is a rope theta or a
* string and whether `f32` is a float, on every load, forever. */
/* A geometry key/value, stored typed, so loading needs no type-guessing parser of
* `Geometry::str()`. */
struct KfParam {
std::string key;
int kind = 0; /* RAD_P_INT | RAD_P_F64 | RAD_P_STR */
@@ -81,21 +71,25 @@ struct KfOperand {
std::vector<int64_t> shape;
bool absent = false;
/* HOW THE INPUT WAS DRAWN. Replay has to reproduce the exact bytes the oracle saw, and the
* draw is not uniform: an index operand is drawn over a range, a cumulative-length operand is
* the batch's shape rather than a draw at all, and a gated-delta-net decay is a cumulative sum
* of log-decays because a normal draw makes the reference overflow. All of that lives in
* OpdShape at record time and none of it is recoverable from the shape alone. */
/* How the input was drawn (copied from OpdShape at record time), so replay reproduces the
* exact bytes; it cannot be recovered from the shape. */
int fill = 0;
bool is_index = false, idx_unique = false, idx_cu = false;
bool is_index = false, idx_unique = false, idx_cu = false, idx_prefix = false;
bool idx_history = false;
int64_t idx_max = 0, idx_const = -1, fill_chunk = 0;
/* A weight table (RAD_OPD_WTAB) in a version-4 recording, which drew it as zeros. Its
* reference was computed on zeros, so the replay draws zeros too; such a case checks nothing
* and is reported as vacuous until the fixture is recorded again. */
bool undrawn = false;
/* A WEIGHT OPERAND IS PLANES OF AN ENCODING (spec §4.3), and a kernel lays it out from those
* planes rather than from the tensor the reference reads. So the recording carries the
* encoding, which planes this operand selects (indices into it) and each one's extents in its
* own elements; the planes are drawn from the operand's seed and the reference reads what
* they decode to (kf_planes_logical). Absent for every other operand, and for a weight
* written by hand in a test, which is then drawn as the tensor it is. */
/* A weight operand is planes of an encoding (spec §4.3), which kernels lay out themselves.
* Recorded: the encoding, the selected plane indices, and each plane's extents in its own
* elements. The planes are drawn from the operand's seed; the reference reads what they decode
* to (kf_planes_logical). Absent for other operands and for hand-written test weights, which
* are drawn as plain tensors.
*
* A weight table (RAD_OPD_WTAB) records one expert's encoding and selection: its shape is
* [n_expert, ...] and each expert's planes are drawn from its own seed (kf_draw_table). */
bool has_enc = false;
RadEncoding enc{};
std::vector<int> sel;
@@ -107,6 +101,7 @@ struct KfOperand {
double ref_sumsq = 0;
int64_t ref_nonfinite = 0;
std::vector<float> sample; /* KF_SAMPLES values at seed-derived positions */
std::vector<double> sketch; /* KF_SKETCH projections (kf_sketch); empty in version 4 */
};
struct KfCase {
@@ -114,70 +109,58 @@ struct KfCase {
std::vector<KfParam> params;
std::vector<KfOperand> opd;
uint64_t seed = 0;
/* THE RANGED PARAMETER'S VALUE, recorded rather than re-derived. The draw needs it as a
* scalar -- a cumulative-length operand divides a token count across sequences -- and the key
* it lives under is the op's own ("M", "q_len", ...). A reader guessing which key to read
* would guess wrong for exactly the ops whose ranged key is unusual. */
/* The ranged parameter's value, recorded because its key varies by op ("M", "q_len", ...).
* The draw needs it, e.g. to divide a token count across sequences. */
int64_t m = 1;
/* The band this point came from, carried for the report only: "M=65 is the bottom of the
* band M in (64, 512]" is most of what makes a tail failure legible. */
/* The band this point came from, for the report only. */
std::string band;
/* A case with no reference: recorded because it is worth TIMING at a real model shape and its
* output is too large to carry. Speed is measurable without an oracle; correctness is not. */
bool speed_only = false;
};
struct Kfixture {
/* 4 carries each weight operand's encoding and selected planes (KfOperand::enc); an earlier
* file has neither and is refused -- record it again. */
uint32_t version = 4;
/* Version 4 carries each weight operand's encoding and selected planes (KfOperand::enc).
* Version 5 adds the sketch, the prefix fill law and drawn weight tables, version 6 the
* sampler laws. Earlier files are refused and must be re-recorded. */
uint32_t version = KF_VERSION;
std::string source; /* the container it was recorded from */
std::string oracle; /* the plugin and version that produced the references */
std::string recorded; /* an ISO date, so a stale fixture is visible */
std::vector<KfCase> cases;
/* load() refuses, as RAD_E_FORMAT, a file it cannot read whole or whose contents cannot
* describe a case: an unknown role, fill law or index flag, a law newer than the file's
* version, a dtype the core cannot size, an extent that is not positive or an element count
* past 2^40, a plane selection without extents, a sample count other than the operand's. A
* corrupt file must not reach an allocation, and an unknown law must not be drawn as another.
*/
int load(const std::string& path);
/* Writes KF_VERSION whatever `version` holds. */
int save(const std::string& path) const;
};
/* The positions sampled in an operand of `n` elements, derived rather than stored. Both the
* recorder and the reader call this, which is the only reason storing just the values works. */
/* The sampled positions in an operand of `n` elements; derived identically by recorder and reader,
* so only values are stored. */
void kf_sample_positions(uint64_t seed, int64_t n, std::vector<int64_t>* out);
/* The seed for operand `k` of a case. One function so record and replay cannot drift. */
/* The seed for operand `k` of a case, shared by record and replay. Inputs use k; an output's
* sample positions and sketch use kf_output_seed. */
uint64_t kf_operand_seed(uint64_t case_seed, int k);
inline uint64_t kf_output_seed(uint64_t case_seed, int k) {
return kf_operand_seed(case_seed, 0x5000 + k);
}
/* ================================================================== drawing an input
*
* ONE IMPLEMENTATION, CALLED BY BOTH SIDES. The recorder and the reader must produce byte-
* identical inputs or every recorded reference is noise, and the draw is not uniform: an index
* operand is drawn over a range that depends on the operand before it, a cumulative-length
* operand is the batch's shape rather than a draw at all, and a gated-delta-net decay is a
* cumulative sum of log-decays because a normal draw makes the reference overflow to 2e38. Two
* copies of that, one in the recorder and one in the reader, is two copies that will differ.
*
* The operand before this one -- `opd[k - 1]` -- supplies an index operand's default range in its
* leading extent; for the first operand there is none. `vocab_rows` is the fallback range in that
* case: a token id has to come from somewhere and the model's vocabulary is where.
*/
/* ================================================================== the weight a kernel reads
*
* A LIBRARY MAY WANT ITS WEIGHTS ARRANGED, AND A FIXTURE CANNOT CARRY EVERY ARRANGEMENT.
*
* libr4d's fp8 GEMMs read their weight in WMMA fragment order and its int4 experts with their
* nibbles reordered; libref reads rows. A container holds neither -- it holds the encoding's
* canonical planes, and each kernel relayouts them at load. The fixture does the same: it carries
* the encoding, draws the planes, and each library runs its own layout hooks over them to get the
* bytes it actually reads, while the reference reads what the planes decode to. Same planes in,
* each kernel's own bytes out, which is what makes one recording serve libraries that disagree.
* Kernels may want weights arranged differently (libr4d's fp8 GEMMs read WMMA fragment order, its
* int4 experts reordered nibbles; libref reads rows). Like a container, the fixture carries the
* encoding's canonical planes; each library lays them out with its own hooks, and the reference
* reads what the planes decode to. One recording thus serves libraries with different layouts.
*/
/* The operand's encoding and selection, from the declaration it was recorded against. */
void kf_operand_enc(const WeightInfo& w, KfOperand* d);
/* A weight operand's selected planes, drawn from `seed`: each dense in its own elements, a row
* starting on a byte, and every value one its role can hold -- a code inside its codebook, a
* permutation that is one, an exponent scale that neither overflows nor vanishes. */
/* A weight operand's selected planes drawn from `seed`: dense in their own elements, rows starting
* on a byte, and every value valid for its role (codes inside the codebook, real permutations,
* exponent scales that neither overflow nor vanish). */
void kf_draw_planes(const KfOperand& d, uint64_t seed, std::vector<std::vector<uint8_t>>* out);
/* What a reference reads for those planes: the operand's dtype and shape (enc_selection_logical).
@@ -185,37 +168,52 @@ void kf_draw_planes(const KfOperand& d, uint64_t seed, std::vector<std::vector<u
int kf_planes_logical(const KfOperand& d, const std::vector<std::vector<uint8_t>>& planes,
std::vector<uint8_t>* out, std::string* why);
/* The bytes kernel `info` reads for operand `operand`, laid out from the planes. RAD_OK with
* `out` holding them and `lay` describing them; RAD_E_UNSUPPORTED when the kernel reads the
* selected plane as it is -- the bytes kf_planes_logical gives, widened if the operand is wider;
* RAD_E_DTYPE when the kernel does not read this encoding at all. Anything else is a decline the
* caller must name rather than absorb. */
/* The bytes kernel `info` reads for `operand`, laid out from the planes. Returns RAD_OK with `out`
* and `lay` filled; RAD_E_UNSUPPORTED when the kernel reads the plane as is (the
* kf_planes_logical bytes, widened if the operand is wider); RAD_E_DTYPE when the kernel does not
* read this encoding. Any other error is a decline the caller must report. */
int kf_lay_weight(const RadKernelInfo* info, const RadParam* p, int n_p, int operand,
const KfOperand& d, const std::vector<std::vector<uint8_t>>& planes,
RadLayout* lay, std::vector<uint8_t>* out);
/* How the engine describes a laid-out weight operand: the STORED dtype with the DECLARED shape.
* Not the RadLayout's shape -- see the comment on the definition. */
/* Describe a laid-out weight operand as the engine does: stored dtype, declared shape (not the
* RadLayout's; see the definition). */
void kf_describe_laid(const KfOperand& d, const RadLayout& lay, void* data, RadTensor* out);
/* The seed a WEIGHT operand is drawn from: its own identity, not the case's. Public because it
* is also the key a caller caches the drawn bytes under -- see kf_draw. */
/* The seed a weight operand is drawn from: its own identity, not the case's. Also the cache key for
* drawn bytes (see kf_draw). */
uint64_t kf_weight_seed(const KfOperand& d, size_t k);
/* THE FALLBACK RANGE FOR AN INDEX OPERAND WITH NOTHING TO INDEX, and it exists so that the
* recorder and the reader cannot disagree about it. The recorder knows the model's vocabulary and
* the reader does not, so a rule that reached for `meta.n_vocab` on one side and something else on
* the other would draw different token ids from the same seed -- a divergence that surfaces as a
* wrong answer in a kernel that is right. Derived from the case itself, identically, on both. */
/* A weight table's logical bytes, [n_expert, ...] in the operand's dtype: expert e's planes drawn
* from the table's identity seed and e, and decoded as kf_planes_logical does. RAD_OK, or the
* refusal with `why`. */
int kf_draw_table(const KfOperand& d, size_t k, std::vector<uint8_t>* out, std::string* why);
/* ================================================================== drawing an input
*
* One implementation for recorder and reader, which must produce byte-identical inputs. An index
* operand's default range is the leading extent of the previous operand, `opd[k - 1]`; the first
* operand falls back to `vocab_rows`.
*/
/* The fallback index range, derived from the case alone so recorder (which knows the model's
* vocabulary) and reader (which does not) agree. */
int64_t kf_vocab_rows(const std::vector<KfOperand>& opd);
/* Draws operand `k`'s bytes. Large plain operands are drawn on every core: the stream is cut into
* RAD_FILL_BLOCK blocks seeded by index, so the bytes do not depend on the thread count. A weight
* table with an encoding goes through kf_draw_table (and an undecodable one comes back zeroed;
* call kf_draw_table to learn why). */
void kf_draw(const std::vector<KfOperand>& opd, size_t k, int64_t M, int64_t vocab_rows,
uint64_t seed, std::vector<uint8_t>* out);
/* The three numbers a reference is reduced to, computed over a widened output. Called by the
* recorder on the ORACLE's output and by the reader on the KERNEL's, so the two are reduced the
* same way. */
/* Reduce a widened output to the reference's three quantities; used on the oracle's output when
* recording and the kernel's when replaying. */
void kf_reduce(const float* v, int64_t n, uint64_t seed, double* sumsq, int64_t* nonfinite,
std::vector<float>* sample);
/* KF_SKETCH projections of the finite elements of `v`, each element's signs derived from `seed`
* and its index. Summed in double, block by block in block order, so the result is independent of
* thread count. */
void kf_sketch(const float* v, int64_t n, uint64_t seed, std::vector<double>* out);
} /* namespace rad */
+12 -22
View File
@@ -1,23 +1,16 @@
#!/bin/sh
# ops_doc_check.sh -- hold docs/OPS.md to the schemas the plugins actually declare.
#
# OPS.md is the authority for the ops it defines, and a document that claims that and is not
# checked will drift: the ways it drifts are quiet ones -- a dropped optional operand,
# a missing `:inout` marker, a parameter that moved into an operand, a section describing a
# parameter no plugin declares. None of those look wrong on the page.
#
# The cost is that an architecture plugin gets written against the DOCUMENT. An op that lives in a
# kernel library and in no schema anyone checked is an op whose caller is guessing, and a document
# that is wrong is worse than one that is missing, because it is read instead of the source.
# OPS.md is the authority for the ops it defines, and architecture plugins are written against it,
# so its drift is caught here: a dropped optional operand, a missing `:inout` marker, a parameter
# that moved into an operand, a parameter no plugin declares.
#
# tools/ops_doc_check.sh docs/OPS.md build/bin/rad-schemas build/radiance_home/kernels/*.so
#
# A row with a FOURTH column is exempt and its marker is printed -- that is how a proposal stays in
# the document without being a lie. Exit 1 on any disagreement; exit 77 -- ctest's
# SKIP_RETURN_CODE -- when a plugin will not dump, so a box without a card reports honestly
# rather than green. The code and not a " SKIP " line, because ctest evaluates
# SKIP_REGULAR_EXPRESSION BEFORE the return code and a skip line would then mask a real
# disagreement found later in the same run.
# A row with a fourth column (a proposal) is exempt and its marker is printed. Exit 1 on any
# disagreement; exit 77 (ctest's SKIP_RETURN_CODE) when a plugin will not dump. A return code, not
# a " SKIP " line: ctest evaluates SKIP_REGULAR_EXPRESSION before the return code, so a skip line
# would mask a disagreement found later in the same run.
set -e
[ $# -ge 3 ] || { echo "usage: $0 <docs/OPS.md> <rad-schemas> <plugin.so>..." >&2; exit 2; }
doc=$1; schemas=$2; shift 2
@@ -37,8 +30,8 @@ function t_param(t, f,o) {
f = (t ~ /:f64$/) ? ":f64" : ""; sub(/:(int|str|f64)$/, "", t); return t f o }
function t_opd(t, q,w,io) {
if (sub(/\?$/, "", t)) q = "?"
# A WEIGHT TABLE is a weight operand whose issue names a RUN of handles, so it is annotated
# apart: `w`wt in the document. See docs/OPS.md and RAD_WTAB in abi/rad_runtime.h.
# A weight table is a weight operand whose issue names a run of handles, annotated apart:
# `w`wt in the document. See docs/OPS.md and RAD_WTAB in abi/rad_runtime.h.
if (sub(/:wtab$/, "", t)) w = "wt"
if (sub(/:weight$/, "", t)) w = "w"
if (sub(/:inout$/, "", t)) io = ":inout"
@@ -59,7 +52,7 @@ function d_opd(t, n,r,w,io,q) {
if (r ~ /:inout/) io = ":inout"
if (r ~ /\?/) q = "?"
return n w io q }
# ---- the dump: FIRST declarer fixes the schema, which is the loader s rule (spec 2.3) -------
# ---- the dump: the first declarer fixes the schema, as in the loader (spec 2.3) -------------
FILENAME != doc {
if ($0 ~ /^ [a-z]/) { op = $1; seen[op] = 1; next }
if ($0 ~ /^ params /) { s = ""; for (i = 2; i <= NF; i++) s = s (i > 2 ? " " : "") t_param($i)
@@ -79,11 +72,8 @@ FILENAME != doc {
os = ""; no = split(oc, oa, /[ \t]+/)
for (i = 1; i <= no; i++) { v = d_opd(oa[i]); if (v != "") os = os (os == "" ? "" : " ") v }
rows++
# An op no loaded plugin declares is not a disagreement, it is a row this CONFIGURATION cannot
# check. A host-only build loads the reference library and no device library, so every
# device-only op in the vocabulary is undeclared here -- and failing on that would make the
# suite red on a machine with no card, which is a supported configuration (spec 18). It is
# counted and named, so the coverage is visible rather than assumed.
# An op no loaded plugin declares is a row this configuration cannot check, not a
# disagreement: a host-only build (spec 18) loads no device library. It is counted and named.
if (!(op in P)) { unchecked++; u_list = u_list (u_list == "" ? "" : " ") op; next }
ok = 1
if (ps != P[op]) { ok = 0; printf "PARAMS %-24s line %d\n doc %s\n real %s\n", op, FNR, ps, P[op] }
+408 -83
View File
@@ -1,18 +1,373 @@
/* opshapes.cpp -- the non-inline half of opshapes.h: dtype widening and the seeded fill.
/* opshapes.cpp -- operand shapes, dtype widening and the seeded fill (opshapes.h).
*
* Shared by rad-kbench and rad-tune. Two copies of a Box-Muller and a bf16 rounding rule is two
* places for them to differ, and a tuner measuring different bytes from the checker is a tuner
* whose numbers describe a program nobody ran.
* Shared by rad-kbench and rad-tune so the tuner and the checker generate identical bytes.
*/
#include "opshapes.h"
#include <thread>
#include <cmath>
#include <cstring>
#include <thread>
namespace rad {
int rad_operand_shapes_hook(const RadKernelInfo* k, const Geometry& g, int n_opd,
std::vector<OpdShape>* out) {
if (!k || !k->opd_shape || n_opd <= 0) return RAD_E_UNSUPPORTED;
out->assign((size_t)n_opd, OpdShape{});
for (int i = 0; i < n_opd; ++i) {
RadOpdDesc d{};
d.idx_const = -1; /* the ABI's "draw" default */
const int st = k->opd_shape(g.params(), g.n_params(), i, &d);
if (st < 0) return st;
/* An inexpressible rank is a hook bug, not a decline; it must not become a zero-extent
* buffer that passes every comparison vacuously. */
if (d.rank == 0 || d.rank > RAD_MAX_RANK) {
if (!(d.flags & RAD_OPD_F_ABSENT)) return RAD_E_SHAPE;
}
OpdShape& o = (*out)[(size_t)i];
o.dtype = d.dtype;
o.shape.assign(d.shape, d.shape + (d.rank <= RAD_MAX_RANK ? d.rank : 0));
o.absent = (d.flags & RAD_OPD_F_ABSENT) != 0;
o.idx_unique = (d.flags & RAD_OPD_F_IDX_UNIQUE) != 0;
o.idx_cu = (d.flags & RAD_OPD_F_IDX_CU) != 0;
o.idx_prefix = (d.flags & RAD_OPD_F_IDX_PREFIX) != 0;
o.idx_history = (d.flags & RAD_OPD_F_IDX_HISTORY) != 0;
o.is_index = d.fill == RAD_FILL_INDEX;
o.idx_max = d.idx_max;
o.idx_const = d.idx_const;
o.fill_chunk = d.fill_chunk;
switch (d.fill) {
case RAD_FILL_SIGMOID: o.fill = OpdShape::FillSigmoid; break;
case RAD_FILL_GATE_CUMSUM: o.fill = OpdShape::FillGateCumsum; break;
case RAD_FILL_TRI_LOWER: o.fill = OpdShape::FillTriLower; break;
case RAD_FILL_UNIT_ROW: o.fill = OpdShape::FillUnitRow; break;
case RAD_FILL_SAMPLE_PARAMS: o.fill = OpdShape::FillSampleParams; break;
default: o.fill = OpdShape::FillNormal; break;
}
for (int64_t e : o.shape) if (e <= 0 && !o.absent) return RAD_E_SHAPE;
}
return RAD_OK;
}
int rad_operand_shapes(const std::string& op, const Geometry& g, int n_opd, int64_t M,
std::vector<OpdShape>* out, const ShapeCtx* ctx) {
auto gi = [&](const char* k, int64_t dflt) {
long long v = 0;
return g.get_i(k, &v) ? (int64_t)v : dflt;
};
/* Activation dtype: `dtype`, else attention's `q_dtype` / `kv_dtype`, else bf16 (the
* project's activation type). Some ops, e.g. `rope` and `qk_norm_rope`, carry no dtype; an
* f32 fallback would make a bf16 kernel refuse the case. */
const char* dts = g.get_s("dtype");
if (!dts) dts = g.get_s("q_dtype");
if (!dts) dts = g.get_s("kv_dtype");
const uint32_t dt = dts ? rad_dtype_parse(dts) : (uint32_t)RAD_BF16;
const uint32_t D = dt == RAD_DT_INVALID ? (uint32_t)RAD_BF16 : dt;
const int64_t n = gi("n", 0);
const int64_t N = gi("N", 0);
const int64_t K = gi("K", 0);
const int64_t group = gi("group", 128);
out->clear();
auto add = [&](uint32_t d, std::vector<int64_t> s, bool idx = false) {
OpdShape o;
o.dtype = d; o.shape = std::move(s); o.is_index = idx;
out->push_back(std::move(o));
};
auto add_fill = [&](uint32_t d, std::vector<int64_t> s, int f, int64_t chunk = 0) {
OpdShape o;
o.dtype = d; o.shape = std::move(s); o.fill = f; o.fill_chunk = chunk;
out->push_back(std::move(o));
};
auto add_idx = [&](std::vector<int64_t> s, int64_t max, int64_t konst = -1,
bool uniq = false) {
OpdShape o;
o.dtype = (uint32_t)RAD_I32; o.shape = std::move(s); o.is_index = true;
o.idx_max = max; o.idx_const = konst; o.idx_unique = uniq;
out->push_back(std::move(o));
};
/* Cumulative sequence lengths for S sequences (OpdShape::idx_cu). */
auto add_cu = [&](int64_t S) { add_idx({S + 1}, 0, -1); out->back().idx_cu = true; };
/* One optional operand this case does not pass. See OpdShape::absent. */
auto skip_opd = [&]() { OpdShape o; o.absent = true; out->push_back(std::move(o)); };
const int64_t head_dim = gi("head_dim", 0);
const int64_t n_head = gi("n_head", 0);
const int64_t n_head_kv = gi("n_head_kv", n_head);
if (op == "rmsnorm") { add(D, {M, n}); add(D, {n}); add(D, {M, n}); }
else if (op == "rope") {
/* One inout operand plus positions. qkv is the fused row: n_head queries and n_head_kv
* each of k and v, all head_dim wide. */
if (head_dim <= 0 || n_head <= 0) return RAD_E_UNSUPPORTED;
add(D, {M, (n_head + 2 * n_head_kv) * head_dim});
add((uint32_t)RAD_I32, {M}, true);
}
else if (op == "rmsnorm_add") { add(D, {M, n}); add(D, {M, n}); add(D, {n});
add(D, {M, n}); add(D, {M, n}); }
else if (op == "layernorm") { add(D, {M, n}); add(D, {n}); add(D, {n}); add(D, {M, n}); }
else if (op == "add" || op == "mul") { add(D, {M, n}); add(D, {M, n}); add(D, {M, n}); }
else if (op == "silu_mul") { add(D, {M, 2 * n}); add(D, {M, n}); }
else if (op == "gelu" || op == "silu" || op == "sigmoid") { add(D, {M, n}); add(D, {M, n}); }
else if (op == "softmax") { add(D, {M, n}); add(D, {M, n}); }
else if (op == "gather_rows") {
/* idx picks M of 4M rows, so the gather is not the identity (which passes while broken). */
add(D, {4 * M, n}); add((uint32_t)RAD_I32, {M}, true); add(D, {M, n});
}
else if (op == "cast") {
const uint32_t from = rad_dtype_parse(g.get_s("from") ? g.get_s("from") : "f32");
const uint32_t to = rad_dtype_parse(g.get_s("to") ? g.get_s("to") : "f32");
add(from ? from : (uint32_t)RAD_F32, {M, n});
add(to ? to : (uint32_t)RAD_F32, {M, n});
}
else if (op == "gemm_nt") { add(D, {M, K}); add(D, {N, K}); add(D, {M, N}); }
else if (op == "gemm_nt_bias") {
/* The optional residual is passed, to cover the epilogue, as libref's description does. */
add(D, {M, K}); add(D, {N, K}); add(D, {N}); add(D, {M, N}); add(D, {M, N});
}
else if (op == "embed_lookup") {
add((uint32_t)RAD_I32, {M}, true);
add(D, {gi("n_vocab", 0), gi("n_embd", 0)});
add(D, {M, gi("n_embd", 0)});
}
else if (op == "logits_gemm") {
add(D, {M, gi("n_embd", 0)});
add(D, {gi("n_vocab", 0), gi("n_embd", 0)});
add((uint32_t)RAD_F32, {M, gi("n_vocab", 0)});
}
else if (op == "quant_act_i8" || op == "had_quant_act_i8") {
/* One scale per row. quant_act_i8's optional `asum` (group-major per-group code sums, rows
* padded to 16) is passed when `group` divides n, as libref describes it. */
add(D, {M, n}); add((uint32_t)RAD_I8, {M, n}); add((uint32_t)RAD_F32, {M, 1});
const int64_t g = gi("group", 0);
if (op == "quant_act_i8") {
if (g > 0 && n % g == 0) add((uint32_t)RAD_F32, {n / g, (M + 15) / 16 * 16});
else skip_opd();
}
}
else if (op == "quant_act_fp8") {
/* quant_act_i8's operands at fp8 width. `dtype` names the (bf16) input. */
if (n <= 0 || group <= 0) return RAD_E_UNSUPPORTED;
add(D, {M, n});
add((uint32_t)RAD_F8E4M3, {M, n});
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. */
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).
* Weights are in libr4d's stored layout and sized in bytes: codes K/2 per row in fragment
* order, exponents [K/32][N], per-row reference [N]. Random bytes suffice for timing. */
if (q && std::strcmp(q, "mxfp4a8") == 0) {
if (N <= 0 || K <= 0 || group != 32) return RAD_E_UNSUPPORTED;
add((uint32_t)RAD_F8E4M3, {M, K});
add((uint32_t)RAD_F32, {M, (K + 127) / 128});
add((uint32_t)RAD_U8, {N, K / 2}); /* b -- e2m1 codes, fragment order */
add((uint32_t)RAD_U8, {K / 32, N}); /* b_scale -- E8M0, [K/32][N] */
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 {
const bool a8 = q && std::strcmp(q, "fp8a8") == 0;
const bool a16 = q && std::strcmp(q, "fp8a16") == 0;
if ((!a8 && !a16) || N <= 0 || K <= 0 || group <= 0) return RAD_E_UNSUPPORTED;
const int64_t kb = (K + group - 1) / group;
const int64_t nb = (N + group - 1) / group;
/* a, a_scale */
if (a8) { add((uint32_t)RAD_F8E4M3, {M, K}); add((uint32_t)RAD_F32, {M, kb}); }
else { add((uint32_t)RAD_BF16, {M, K}); skip_opd(); }
add((uint32_t)RAD_F8E4M3, {N, K}); /* b -- the checkpoint's own bytes */
add((uint32_t)RAD_BF16, {nb, kb}); /* b_scale -- weight_scale_inv, one per 128x128 */
add((uint32_t)RAD_BF16, {M, N}); /* y */
skip_opd(); /* a_sum */
skip_opd(); /* b_ref */
}
}
else if (op == "dequant") {
add((uint32_t)RAD_I8, {M, n}); add((uint32_t)RAD_F32, {M, group ? n / group : 1});
add(D, {M, n});
}
else if (op == "all_reduce" || op == "all_gather") {
/* all_gather's second operand is [world_size * numel]. all_reduce's is the optional second
* destination (absent means in place, the usual form); it is passed to exercise the
* out-of-place form. */
const int64_t numel = gi("numel", n ? n : M);
add(D, {numel});
add(D, {op == "all_gather" ? numel * gi("world_size", 1) : numel});
}
/* ---- the paged pair, sharing the layout stated in libref/ref_ops.h:
*
* kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim] K first, V second in a slot
*
* The block count and context length are this tool's choice; any cache large enough for the
* case works as long as the indices land inside it. */
else if (op == "kv_store") {
const int64_t bs = gi("block_size", 0);
const int64_t kvh = gi("n_head_kv", 0);
if (bs <= 0 || kvh <= 0 || head_dim <= 0) return RAD_E_UNSUPPORTED;
/* Two blocks of slack so the slot mapping is not a dense prefix, which would not test the
* block index. */
const int64_t nb = (M + bs - 1) / bs + 2;
/* Only the cache takes `kv_dtype`; k and v are always bf16 (D would fall back to
* kv_dtype). */
const char* kvs = g.get_s("kv_dtype");
const uint32_t kvd = kvs ? rad_dtype_parse(kvs) : (uint32_t)RAD_DT_INVALID;
add((uint32_t)RAD_BF16, {M, kvh, head_dim});
add((uint32_t)RAD_BF16, {M, kvh, head_dim});
add_idx({M}, nb * bs, -1, /*uniq*/ true);
add(kvd == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_BF16 : kvd, {nb, kvh, bs, 2 * head_dim});
}
else if (op == "attn_paged") {
/* `M` is q_len (decode and prefill are different kernels, docs/OPS.md). One sequence whose
* context is exactly this query: causal attention over its own prefix, as a prefill chunk
* runs. */
const int64_t bs = gi("block_size", 16);
const int64_t gqa = gi("gqa", 1);
const int64_t nh = gi("n_head", gqa);
if (bs <= 0 || gqa <= 0 || nh <= 0 || head_dim <= 0 || nh % gqa) return RAD_E_UNSUPPORTED;
const int64_t kvh = nh / gqa;
const int64_t n_seq = 1, ctx = M;
const int64_t max_blocks = (ctx + bs - 1) / bs;
add(D, {n_seq * M, nh, head_dim});
add(D, {max_blocks, kvh, bs, 2 * head_dim});
add_idx({n_seq, max_blocks}, max_blocks);
/* seqused is fixed, not drawn (see OpdShape::idx_const). */
add_idx({n_seq}, 0, ctx);
skip_opd(); /* k_descale -- this cache is not quantised */
skip_opd(); /* v_descale */
skip_opd(); /* cu_seqlens -- one sequence, read rectangular */
add(D, {n_seq * M, nh, head_dim});
}
/* ---- gated delta net. The layouts are libref/ref_gdn.cpp's, stated there once:
*
* q, k [T, Hk, head_k] v, o [T, Hv, head_v]
* g, beta [T, Hv] fp32 A [T, Hv, chunk]
* h0, ht [N, Hv, head_v, head_k] fp32 cu [N+1]
* conv w [conv_dim, conv_width] conv_state [n_slots, conv_dim, state_len]
*
* with conv_dim = 2 * Hk * head_k + Hv * head_v.
*
* Head counts are not op parameters; they come from container metadata via `ctx`. Without
* them the op is skipped, not guessed. */
else if (op.rfind("gdn_", 0) == 0 && op != "gdn_gated_rmsnorm") {
if (!ctx || ctx->n_head_k <= 0 || ctx->n_head_v <= 0) return RAD_E_UNSUPPORTED;
const int64_t Hk = ctx->n_head_k, Hv = ctx->n_head_v;
const int64_t hk = gi("head_k", 0), hv = gi("head_v", hk);
const int64_t chunk = gi("chunk", 64);
const int64_t width = gi("conv_width", 4);
if (hk <= 0 || hv <= 0 || chunk <= 0 || width <= 1) return RAD_E_UNSUPPORTED;
const int64_t conv_dim = 2 * Hk * hk + Hv * hv;
const int64_t S = ctx->n_seq > 0 ? ctx->n_seq : 1;
if (op == "gdn_conv_prep") {
/* T tokens over S sequences, one conv-state slot each. The state length is
* conv_width - 1 + n_spec, i.e. conv_width - 1 without speculation. */
add(D, {M, conv_dim}); /* x -- the fused projection row */
add(D, {conv_dim, width}); /* w */
skip_opd(); /* b -- this checkpoint has no conv bias */
add((uint32_t)RAD_F32, {Hv}); /* A_log */
add((uint32_t)RAD_F32, {Hv}); /* dt_bias */
add(D, {S, conv_dim, width - 1}); /* conv_state, INOUT */
add_cu(S); /* cu */
add(D, {M, Hv}); /* a */
add(D, {M, Hv}); /* b_gate */
add_idx({S}, S, -1, /*uniq*/ true); /* cache_idx -- one slot a sequence */
add_idx({S}, 0, 0); /* has_init -- cold prefill, passed
* explicitly: ref reads a null as warm,
* libr4d as cold. */
add(D, {M, Hk, hk}); /* q */
add(D, {M, Hk, hk}); /* k */
add(D, {M, Hv, hv}); /* v */
add_fill((uint32_t)RAD_F32, {M, Hv}, OpdShape::FillGateCumsum, chunk); /* g */
add_fill((uint32_t)RAD_F32, {M, Hv}, OpdShape::FillSigmoid); /* beta */
}
else if (op == "gdn_kkt_solve") {
add(D, {M, Hk, hk}); /* k */
add_fill((uint32_t)RAD_F32, {M, Hv}, OpdShape::FillSigmoid); /* beta */
add_fill((uint32_t)RAD_F32, {M, Hv}, OpdShape::FillGateCumsum, chunk); /* g */
add_cu(S); /* cu */
add_fill(D, {M, Hv, chunk}, OpdShape::FillTriLower, chunk); /* A */
}
else if (op == "gdn_chunk_scan") {
add(D, {M, Hk, hk}); /* q */
add(D, {M, Hk, hk}); /* k */
add(D, {M, Hv, hv}); /* v */
add_fill(D, {M, Hv, chunk}, OpdShape::FillTriLower, chunk); /* A */
add_fill((uint32_t)RAD_F32, {M, Hv}, OpdShape::FillGateCumsum, chunk); /* g */
add_fill((uint32_t)RAD_F32, {M, Hv}, OpdShape::FillSigmoid); /* beta */
add((uint32_t)RAD_F32, {S, Hv, hv, hk}); /* h0 */
add_cu(S); /* cu */
add(D, {M, Hv, hv}); /* o */
add((uint32_t)RAD_F32, {S, Hv, hv, hk}); /* ht */
add_idx({S}, S, -1, /*uniq*/ true); /* state_idx */
}
else if (op == "gdn_conv_update") {
/* Decode. `M` is q_len, one row per candidate token; the window is
* conv_width - 2 + q_len deep so a rejection only moves the read offset (ref_ops.h's
* rollback contract). num_accepted is 1-based; all ones is non-speculative decode. */
const int64_t sl = width - 2 + M;
add(D, {S * M, conv_dim}); /* x */
add(D, {conv_dim, width}); /* w */
skip_opd(); /* b */
add(D, {S, conv_dim, sl}); /* conv_state, INOUT */
add_idx({S, M}, S, -1); /* state_idx */
add_idx({S}, 0, 1); /* num_accepted -- none rejected */
add_cu(S); /* cu */
add(D, {S * M, Hk, hk}); /* q */
add(D, {S * M, Hk, hk}); /* k */
add(D, {S * M, Hv, hv}); /* v */
}
else if (op == "gdn_recurrent_update") {
add(D, {S * M, Hk, hk}); /* q */
add(D, {S * M, Hk, hk}); /* k */
add(D, {S * M, Hv, hv}); /* v */
add(D, {S * M, Hv}); /* a */
add(D, {S * M, Hv}); /* b */
add((uint32_t)RAD_F32, {Hv}); /* A_log */
add((uint32_t)RAD_F32, {Hv}); /* dt_bias */
add((uint32_t)RAD_F32, {S * M, Hv, hv, hk}); /* state, one per candidate token */
add_idx({S, M}, S * M, -1, /*uniq*/ true); /* state_idx */
add_idx({S}, 0, 1); /* num_accepted */
add_cu(S); /* cu */
add(D, {S * M, Hv, hv}); /* z */
add((uint32_t)RAD_F32, {hv}); /* norm_w */
add(D, {S * M, Hv, hv}); /* o */
skip_opd(); /* o_q -- the folded fp8 quantiser */
skip_opd(); /* o_scale */
}
else return RAD_E_UNSUPPORTED;
}
else if (op == "gdn_gated_rmsnorm") {
/* One row per (token, head): `M` is already tokens x heads and `channels` is head_v. */
const int64_t ch = gi("channels", 0);
if (ch <= 0) return RAD_E_UNSUPPORTED;
add(D, {M, ch}); add(D, {M, ch}); add((uint32_t)RAD_F32, {ch}); add(D, {M, ch});
}
/* Deliberately absent: ssm_conv and qk_norm_rope_gate take extents from the KV group's state
* geometry and from interleaved strided views (attn_q is [n_embd, 2*head_dim*n_head] with query
* and gate alternating per head). Only the kernel's hook can describe them. */
else return RAD_E_UNSUPPORTED;
if ((int)out->size() != n_opd) {
/* Recipe and schema disagree: a bug in one of them. Do not pad with a guess. */
RAD_DEBUG("%s: shape recipe produces %zu operands, the schema declares %d",
op.c_str(), out->size(), n_opd);
return RAD_E_UNSUPPORTED;
}
for (const OpdShape& s : *out)
for (int64_t d : s.shape)
if (d <= 0) return RAD_E_UNSUPPORTED;
return RAD_OK;
}
void rad_widen(const void* src, uint32_t dtype, int64_t n, std::vector<float>* out) {
out->assign((size_t)n, 0.0f);
switch (dtype) {
@@ -34,8 +389,8 @@ void rad_widen(const void* src, uint32_t dtype, int64_t n, std::vector<float>* o
const uint32_t e = (h >> 10) & 0x1F, m = h & 0x3FF;
uint32_t bits;
if (e == 0) {
/* Subnormal. Renormalise rather than flush: a flushed small weight is a wrong
* one, and it is wrong in a way that never trips a norm-based tolerance. */
/* Subnormal: renormalise rather than flush; a flushed value would pass a
* norm-based tolerance while wrong. */
if (m == 0) bits = sign;
else {
int sh = -1;
@@ -53,13 +408,9 @@ void rad_widen(const void* src, uint32_t dtype, int64_t n, std::vector<float>* o
(*out)[(size_t)i] = f;
}
break;
/* OCP fp8. These two are what make the block-scaled fp8 family checkable at all, and
* without them it fails VACUOUSLY rather than visibly: rad_narrow would leave the E4M3
* activation at its zero fill, so kernel and oracle both compute zero, rad_widen reads the
* E4M3 output back as zero, and every case reports rel_l2 = 0 and "ok". A vacuous pass is
* worse than a skip, which is what the `default` below is careful to produce for a dtype
* whose bytes only its own kernel understands. e4m3 has no infinity and S1111111 is its
* only NaN; e5m2 is IEEE-shaped. */
/* OCP fp8. Without these the fp8 family would pass vacuously: inputs and outputs would
* all read as zero. e4m3 has no infinity and S1111111 is its only NaN; e5m2 is
* IEEE-shaped. */
case RAD_F8E4M3:
for (int64_t i = 0; i < n; ++i) {
const uint8_t b = ((const uint8_t*)src)[i];
@@ -117,18 +468,10 @@ void rad_widen(const void* src, uint32_t dtype, int64_t n, std::vector<float>* o
case RAD_I32:
for (int64_t i = 0; i < n; ++i) (*out)[(size_t)i] = (float)((const int32_t*)src)[i];
break;
/* THE INTEGER TYPES MUST BE READABLE HERE OR A COMPARISON AGAINST THEM IS VACUOUS.
*
* An output operand is widened on the recorder's side and again on the reader's, so a
* dtype that falls through to `default` is reduced to a norm of zero and a sample of
* zeros on BOTH sides -- which agrees perfectly and reports as a pass. A kernel writing
* arbitrary bytes into such an operand is indistinguishable from a correct one.
*
* The set is the one libref's own element accessor reads, because libref is what the
* recording is of: a dtype the oracle can produce and this cannot is an output nothing
* checks. i64 past 2^24 does not survive the float this widens into, which is the same
* bound rad_narrow documents and is fine for what these operands carry (sizes, offsets,
* token ids below a quarter-million vocabulary). */
/* Integer types must be readable here: an unhandled dtype widens to zeros on both the
* recorder's and the reader's side, so any output would pass. The set matches what
* libref's element accessor reads. i64 is exact only up to 2^24 in float, enough for
* what these operands carry (sizes, offsets, token ids). */
case RAD_I16:
for (int64_t i = 0; i < n; ++i) (*out)[(size_t)i] = (float)((const int16_t*)src)[i];
break;
@@ -142,26 +485,28 @@ void rad_widen(const void* src, uint32_t dtype, int64_t n, std::vector<float>* o
for (int64_t i = 0; i < n; ++i) (*out)[(size_t)i] = ((const uint8_t*)src)[i] ? 1.0f : 0.0f;
break;
default:
/* A plugin-private dtype: only its own kernel knows what the bytes mean. Zeroed, and
* the caller sees a zero reference and reports it as such rather than as agreement. */
/* Plugin-private dtype: left zeroed; the caller reports a zero reference as such. */
break;
}
}
/* Fixture inputs are redrawn from recorded seeds (kfixture.h), so every rounding below is part of
* the recorded contract: changing one invalidates the recorded cases of that dtype. */
void rad_narrow(const float* src, uint32_t dtype, int64_t n, void* dst) {
switch (dtype) {
case RAD_F32:
std::memcpy(dst, src, (size_t)n * 4);
break;
case RAD_BF16:
/* Round-to-nearest-even, the same rule rad-convert uses. Truncating here would bias
* every generated input toward zero and quietly flatter every kernel. */
/* Round-to-nearest-even, as rad-convert does; truncation would bias inputs toward
* zero. */
for (int64_t i = 0; i < n; ++i) {
uint32_t b;
std::memcpy(&b, &src[i], 4);
((uint16_t*)dst)[i] = (uint16_t)((b + 0x7FFFu + ((b >> 16) & 1u)) >> 16);
}
break;
/* f16 and e5m2 truncate and flush subnormals to zero. */
case RAD_F16:
for (int64_t i = 0; i < n; ++i) {
uint32_t x;
@@ -176,11 +521,8 @@ void rad_narrow(const float* src, uint32_t dtype, int64_t n, void* dst) {
((uint16_t*)dst)[i] = h;
}
break;
/* The encode side of the pair above. `rad_fill_normal` draws unit normals and E4M3 holds
* 448, so no scaling is applied -- the values land in the middle of the format's range,
* which is where a quantised GEMM actually operates. Round-to-nearest-even on the 3-bit
* mantissa with a real subnormal path, matching libref/ref_common.h; truncating would
* bias every generated input toward zero and flatter every kernel. */
/* Unit normals fit E4M3 (max 448) unscaled. Round-to-nearest-even on the 3-bit mantissa
* with a subnormal path, matching libref/ref_common.h. */
case RAD_F8E4M3:
for (int64_t i = 0; i < n; ++i) {
float a = src[i] < 0 ? -src[i] : src[i];
@@ -220,6 +562,7 @@ void rad_narrow(const float* src, uint32_t dtype, int64_t n, void* dst) {
((uint8_t*)dst)[i] = h;
}
break;
/* Unit normals scaled by 32 to spread over the int8 range. */
case RAD_I8:
for (int64_t i = 0; i < n; ++i) {
float v = src[i] * 32.0f;
@@ -237,24 +580,15 @@ void rad_narrow(const float* src, uint32_t dtype, int64_t n, void* dst) {
case RAD_I32:
for (int64_t i = 0; i < n; ++i) ((int32_t*)dst)[i] = (int32_t)std::lrintf(src[i]);
break;
/* i64 MUST BE HANDLED HERE, because the `default` below zeroes: an unhandled i64 operand
* is drawn as a buffer of zeros, silently, since zero is a legal value for most of them.
* The ops that do check read them as sizes -- ngram_ids refuses `vocab_size <= 0` by name,
* so with zeroed sizes it would be refused at every geometry and never checked on any
* plugin, and that refusal reads exactly like a shape the reference does not serve.
/* Integer types must be handled here, since `default` zeroes silently; e.g. ngram_ids
* refuses `vocab_size <= 0`, so zeroed sizes would skip it at every geometry. Keep this
* set in step with rad_widen.
*
* `llrintf` and not `lrintf`: long is 32-bit on some targets and this type is not.
* A float carries 24 bits, so a drawn i64 past 2^24 does not round-trip -- which is fine
* for what i64 operands in this vocabulary actually are (sizes, offsets, multipliers) and
* is why the shapes that need a large exact value pass it as idx_const rather than a draw. */
* `llrintf`, not `lrintf`: long is 32-bit on some targets. Values past 2^24 do not
* round-trip through float; shapes needing a large exact value use idx_const. */
case RAD_I64:
for (int64_t i = 0; i < n; ++i) ((int64_t*)dst)[i] = (int64_t)std::llrintf(src[i]);
break;
/* The rest of the integer vocabulary, for the reason the i64 note above gives and with
* the same consequence: zeroed by `default`, an operand of one of these types is handed
* to the kernel as a buffer of zeros, which is a legal value for most of them and so
* never reports as anything. Kept in step with rad_widen -- a type this can write and
* that cannot read back is an output whose comparison is vacuous. */
case RAD_I16:
for (int64_t i = 0; i < n; ++i) ((int16_t*)dst)[i] = (int16_t)std::lrintf(src[i]);
break;
@@ -282,21 +616,13 @@ uint64_t rad_case_seed(uint64_t base, std::string_view op, int band, int domain,
return h ? h : 1;
}
/* Standard normal by Box-Muller. Activations in a transformer are roughly Gaussian, and the tails
* are the point: an outlier is what breaks a per-row scale, and a uniform fill has none. */
/* BLOCK-SEEDED AND THREADED, and the block seeding is what makes the threading legal.
/* Standard normals by Box-Muller: transformer activations are roughly Gaussian, and the tails
* (outliers that break a per-row scale) matter, which a uniform fill lacks.
*
* This is the hot loop of the whole tool: a replay draws every operand of every case, and an fp8
* GEMM weight at N=34816 K=5120 is 178 million elements of Box-Muller -- four transcendentals per
* pair, chained through one splitmix state. Single threaded that is most of a replay's wall clock,
* and a benchmark that spends its time generating its own inputs is a benchmark nobody runs.
*
* The chain is the problem: element i depends on element i-2, so nothing can be split. So the
* stream is cut into fixed blocks and each block derives its OWN seed from (seed, block index).
* The values then do not depend on how many threads ran, or on whether any did -- which is not a
* nicety here but the contract: a fixture recorded on one machine is replayed on another, and a
* draw that varied with core count would make every recorded reference wrong somewhere else.
*/
* This is the replay's hot loop (an fp8 GEMM weight at N=34816 K=5120 is 178M elements), so it is
* threaded. One splitmix chain cannot be split, so the stream is cut into fixed blocks, each seeded
* from (seed, block index). Values are then independent of thread count, which the contract
* requires: fixtures recorded on one machine are replayed on another. */
const int64_t RAD_FILL_BLOCK = 1 << 16;
static void fill_block(float* p, int64_t n, uint64_t seed, float sigma) {
@@ -315,33 +641,32 @@ static uint64_t block_seed(uint64_t seed, int64_t b) {
return rad_splitmix(s);
}
/* ONE BLOCK OF THAT STREAM, for a caller drawing a large operand a block at a time so the float
* intermediate never gets as big as the tensor. Same seed, same block index, same bytes. */
/* One block of that stream, for callers drawing a large operand block by block to bound the float
* intermediate. Same seed and block index give the same bytes. */
void rad_fill_normal_block(float* p, int64_t n, uint64_t seed, int64_t block, float sigma) {
fill_block(p, n, block_seed(seed, block), sigma);
}
void rad_fill_normal(float* p, int64_t n, uint64_t seed, float sigma) {
if (n <= 0) return;
const int64_t nb = (n + RAD_FILL_BLOCK - 1) / RAD_FILL_BLOCK;
if (nb == 1) { fill_block(p, n, block_seed(seed, 0), sigma); return; }
unsigned hw = std::thread::hardware_concurrency();
if (hw == 0) hw = 1;
const int64_t nthreads = std::min<int64_t>(nb, (int64_t)hw);
std::vector<std::thread> th;
th.reserve((size_t)nthreads);
for (int64_t t = 0; t < nthreads; ++t) {
th.emplace_back([&, t]() {
for (int64_t b = t; b < nb; b += nthreads) {
const int64_t lo = b * RAD_FILL_BLOCK;
fill_block(p + lo, std::min<int64_t>(RAD_FILL_BLOCK, n - lo),
block_seed(seed, b), sigma);
}
});
rad_for_blocks((n + RAD_FILL_BLOCK - 1) / RAD_FILL_BLOCK, [&](int64_t b) {
const int64_t lo = b * RAD_FILL_BLOCK;
fill_block(p + lo, std::min<int64_t>(RAD_FILL_BLOCK, n - lo), block_seed(seed, b), sigma);
});
}
void rad_for_blocks(int64_t nb, const std::function<void(int64_t)>& fn) {
const unsigned hw = std::thread::hardware_concurrency();
const int64_t nt = std::min<int64_t>(nb, hw ? (int64_t)hw : 1);
if (nt <= 1) {
for (int64_t b = 0; b < nb; ++b) fn(b);
return;
}
std::vector<std::thread> th;
th.reserve((size_t)nt);
for (int64_t t = 0; t < nt; ++t)
th.emplace_back([&, t]() { for (int64_t b = t; b < nb; b += nt) fn(b); });
for (auto& x : th) x.join();
}
} /* namespace rad */
+54 -458
View File
@@ -1,28 +1,18 @@
/* opshapes.h -- how big is operand i of this op, given its resolved geometry.
/* opshapes.h -- the extent of operand i of an op, given its resolved geometry.
*
* THE ONE PLACE THE TOOLS KNOW SOMETHING ABOUT AN OP, AND THEY SHOULD NOT HAVE TO.
* A schema names operands and roles but not extents, which the run phase supplies at issue. Tools
* that call an op cold (rad-kbench, rad-tune) need them to size buffers. The kernel's
* RadKernelInfo::opd_shape hook is asked first (rad_operand_shapes_hook); the fallback recipes
* (rad_operand_shapes) cover the docs/OPS.md ops whose shapes follow from their parameters. Ops covered by neither are
* skipped and counted by the caller, never guessed: an invented extent tests bounds handling, not
* correctness.
*
* An op's schema names its operands and their roles but not their extents, and the extents are
* not derivable from the parameters in general -- the run phase supplies them at issue. So a tool
* that wants to CALL an op cold, which rad-kbench and rad-tune both do, has to size its buffers
* somehow, and the honest options are a table here or a hook on RadKernelInfo.
*
* The hook is the better answer: a `RadShapeFn` beside RadLayoutFn, asking the kernel to describe
* operand i for a geometry (see rad_operand_shapes_hook below). libref implements every op in the
* conventional vocabulary, so once ref supplies the hook for all of them this file can go away.
* Until then this covers the vocabulary in docs/OPS.md whose shapes follow from its
* parameters, and every op it does not cover is SKIPPED AND COUNTED by its caller rather than
* guessed at -- a tool that invents an extent tests the kernel's bounds handling and calls the
* result correctness.
*
* Shared by rad-kbench and rad-tune so the two cannot disagree about what shape a case is; a
* tuning measurement taken at a different extent from the correctness check is a measurement of
* something else.
* Shared by rad-kbench and rad-tune so a tuning case and its correctness check use the same shape.
*/
#pragma once
#include "iface.h"
#include <cstring>
#include <functional>
#include <string>
#include <vector>
@@ -32,51 +22,41 @@ struct OpdShape {
uint32_t dtype = RAD_F32;
std::vector<int64_t> shape;
bool is_index = false; /* token ids / row indices, not normals */
/* AN INDEX OPERAND'S RANGE, when it is not the previous operand's leading extent. A KV slot
* indexes n_blocks * block_size positions and a block-table entry indexes n_blocks, and neither
* is any operand's dim 0 -- drawing them from the wrong range gives a case that tests the
* kernel's out-of-range handling and calls the result correctness. 0 keeps the default. */
/* Index range when it is not the previous operand's leading extent: a KV slot indexes
* n_blocks * block_size positions, a block-table entry n_blocks. 0 keeps the default. */
int64_t idx_max = 0;
/* A CONSTANT, for an index operand whose value is a length rather than a choice. `seqused` is
* the one: a random context length shorter than the query makes a causal attention read a
* prefix that does not exist, which both implementations would then agree about while neither
* computed what the model asks for. -1 keeps the draw. */
/* A constant for an index operand that is a length, not a choice (`seqused`): a random
* context shorter than the query would make causal attention read a nonexistent prefix. -1
* keeps the draw. */
int64_t idx_const = -1;
/* DISTINCT indices, for a SCATTER. `slot_mapping` is the case: two tokens drawn onto the same
* slot make the store a race, and the two implementations resolve it differently -- ref runs
* the token loop under OpenMP and the kernel runs a workgroup a token -- so the comparison
* measures the scheduler rather than the kernel. A read-side index (a gather row, a block
* table entry) may repeat and does. */
/* Distinct indices for a scatter (`slot_mapping`): two tokens on one slot race, and ref and
* the kernel resolve the race differently. Read-side indices may repeat. */
bool idx_unique = false;
/* CUMULATIVE SEQUENCE LENGTHS: [0, ..., T]. Every GDN op takes `cu` and opens by reading it,
* so it is not optional and it is not a draw -- it is the batch's shape. */
/* Cumulative sequence lengths [0, ..., T] (`cu` of the GDN ops): the batch shape, not a draw. */
bool idx_cu = false;
/* THE DOMAIN OF A NON-INDEX OPERAND, where a normal draw is outside it. `beta` is a sigmoid
* output in (0, 1) and `g` is an intra-chunk cumulative sum of log-decays, non-increasing and
* never positive -- and the gated-delta-net scan depends on that: every decay factor it forms
* is e^{g_i - g_j} with j <= i, which is <= 1 only because g is monotone. Feeding it normals
* makes the ORACLE overflow to 2e38 while the kernel does something else, and the comparison
* then measures the test. RAD_GDN_CHUNK carries the chunk width the cumsum resets at. */
enum Fill { FillNormal = 0, FillSigmoid, FillGateCumsum, FillTriLower, FillUnitRow };
/* A routing histogram's offsets [0, ..., idx_max - 1] (RAD_OPD_F_IDX_PREFIX). */
bool idx_prefix = false;
/* A token history whose rows repeat themselves (RAD_OPD_F_IDX_HISTORY). */
bool idx_history = false;
/* Value domain of a non-index operand when normals fall outside it. `beta` is a sigmoid
* output in (0, 1); `g` is an intra-chunk cumulative sum of log-decays, non-increasing and
* non-positive, so every GDN decay factor e^{g_i - g_j} (j <= i) is <= 1. With normals the
* oracle overflows. fill_chunk is the chunk width where the cumsum resets (RAD_GDN_CHUNK).
* FillSampleParams writes sampler rows (RAD_FILL_SAMPLE_PARAMS); for it fill_chunk is the
* history width and idx_max the bitmask's row count. */
enum Fill { FillNormal = 0, FillSigmoid, FillGateCumsum, FillTriLower, FillUnitRow,
FillSampleParams };
int fill = FillNormal;
int64_t fill_chunk = 0;
/* An OPTIONAL operand this case deliberately does not pass. The recipe still has to emit one
* entry per schema operand -- the count check below is what catches a recipe that has drifted
* from the schema -- so "absent" needs a spelling, and a null RadTensor is exactly what the
* ABI already means by it (rad_abi.h). The caller allocates nothing and compares nothing.
*
* It earns its keep on `quant_act_i8`, whose third output selects libr4d's `_asum` form:
* libref implements no asymmetric grid, so it does not produce those sums, and passing
* the buffer anyway would compare a zeroed reference against a real one and report a failure
* that is a gap in the ORACLE rather than a fault in the kernel. */
/* An optional operand this case does not pass; it is a null RadTensor (rad_abi.h), and the
* caller allocates and compares nothing. Recipes still emit one entry per schema operand, so
* the count check catches schema drift. Used for `quant_act_i8`'s third output. */
bool absent = false;
};
/* What the OPS DO NOT SAY and a recipe still needs. The gated-delta-net family reads its head
* counts off the operands, so no op names them and no geometry carries them -- and a check run at
* an invented head ratio is a check of a model nobody is running. The caller reads them from the
* container's metadata and passes them here; absent, the gdn_* recipes decline and their cases are
* skipped and counted, which is this file's rule everywhere else. */
/* Model facts no op parameter carries. The GDN ops read head counts off the operands, so the caller
* passes them from the container metadata; without them the gdn_* recipes decline (skipped and
* counted). */
struct ShapeCtx {
int64_t n_head_k = 0; /* linear_num_key_heads */
int64_t n_head_v = 0; /* linear_num_value_heads */
@@ -85,409 +65,23 @@ struct ShapeCtx {
/* ================================================================== the hook, which wins
*
* ASK THE KERNEL FIRST. `RadKernelInfo::opd_shape` is the hook this file's header describes: the
* component that knows an operand's extent is the one that reads it, and a table in `tools/` can
* only ever describe the ops whoever wrote the table had heard of. Everything below this function
* is the fallback for a plugin that does not implement the hook.
* Ask the kernel first via `RadKernelInfo::opd_shape`; rad_operand_shapes is the fallback for
* plugins without the hook. The caller chooses which kernel to ask:
*
* WHICH kernel to ask is a real choice and it is the caller's:
* - a correctness check asks the oracle, so both implementations get the same bytes under the
* reference semantics;
* - a benchmark asks the kernel under test, since a device-only fusion has no oracle.
*
* - A CORRECTNESS check wants the ORACLE's description. The two implementations have to be
* handed the same bytes for the comparison to mean anything, and where they disagree about an
* extent the reference semantics are the ones that define the op.
* - A BENCHMARK wants the KERNEL UNDER TEST's own. A device-only fusion has no oracle at all --
* which is why a large part of an accelerated library is reachable only this way -- and timing
* one still needs buffers.
*
* So this takes the RadKernelInfo to ask rather than deciding, and returns RAD_E_UNSUPPORTED if
* that kernel has no hook or declines the geometry. A decline is a real answer and the caller
* SKIPS AND COUNTS it; only a caller that invents an extent is wrong, because it then tests the
* kernel's bounds handling and calls the result correctness. */
inline int rad_operand_shapes_hook(const RadKernelInfo* k, const Geometry& g, int n_opd,
std::vector<OpdShape>* out) {
if (!k || !k->opd_shape || n_opd <= 0) return RAD_E_UNSUPPORTED;
out->assign((size_t)n_opd, OpdShape{});
for (int i = 0; i < n_opd; ++i) {
RadOpdDesc d{};
d.idx_const = -1; /* the ABI's "draw", so a hook that leaves it alone means the default */
const int st = k->opd_shape(g.params(), g.n_params(), i, &d);
if (st < 0) return st;
/* A rank the ABI cannot express is a hook bug, not a geometry it declined, and it must not
* become a zero-extent buffer that every comparison then passes vacuously. */
if (d.rank == 0 || d.rank > RAD_MAX_RANK) {
if (!(d.flags & RAD_OPD_F_ABSENT)) return RAD_E_SHAPE;
}
OpdShape& o = (*out)[(size_t)i];
o.dtype = d.dtype;
o.shape.assign(d.shape, d.shape + (d.rank <= RAD_MAX_RANK ? d.rank : 0));
o.absent = (d.flags & RAD_OPD_F_ABSENT) != 0;
o.idx_unique = (d.flags & RAD_OPD_F_IDX_UNIQUE) != 0;
o.idx_cu = (d.flags & RAD_OPD_F_IDX_CU) != 0;
o.is_index = d.fill == RAD_FILL_INDEX;
o.idx_max = d.idx_max;
o.idx_const = d.idx_const;
o.fill_chunk = d.fill_chunk;
switch (d.fill) {
case RAD_FILL_SIGMOID: o.fill = OpdShape::FillSigmoid; break;
case RAD_FILL_GATE_CUMSUM: o.fill = OpdShape::FillGateCumsum; break;
case RAD_FILL_TRI_LOWER: o.fill = OpdShape::FillTriLower; break;
case RAD_FILL_UNIT_ROW: o.fill = OpdShape::FillUnitRow; break;
default: o.fill = OpdShape::FillNormal; break;
}
for (int64_t e : o.shape) if (e <= 0 && !o.absent) return RAD_E_SHAPE;
}
return RAD_OK;
}
* Returns RAD_E_UNSUPPORTED if the kernel has no hook or declines the geometry; the caller skips
* and counts the case. */
int rad_operand_shapes_hook(const RadKernelInfo* k, const Geometry& g, int n_opd,
std::vector<OpdShape>* out);
/* Fills one entry per schema operand, in order. RAD_E_UNSUPPORTED when this op has no recipe or
* the geometry does not carry the parameters the recipe needs. `M` is the value of the ranged
* parameter for the band being sized. */
inline int rad_operand_shapes(const std::string& op, const Geometry& g, int n_opd, int64_t M,
std::vector<OpdShape>* out, const ShapeCtx* ctx = nullptr) {
auto gi = [&](const char* k, int64_t dflt) {
long long v = 0;
return g.get_i(k, &v) ? (int64_t)v : dflt;
};
/* THE ACTIVATION DTYPE, and the fallback matters. Several ops carry no `dtype` parameter at
* all -- `rope` and `qk_norm_rope` name a `mode` and a `theta` and nothing about the width,
* because the tensor they rotate in place is whatever the caller declared. Falling back to f32
* there manufactures an f32 activation, which a shim that reads a bf16 rotation refuses on
* dtype -- a check reporting FAIL on a kernel the engine runs correctly. `q_dtype` and
* `kv_dtype` are attention's spellings of the same thing, and bf16 is what every activation in
* this project is when nothing says otherwise. */
const char* dts = g.get_s("dtype");
if (!dts) dts = g.get_s("q_dtype");
if (!dts) dts = g.get_s("kv_dtype");
const uint32_t dt = dts ? rad_dtype_parse(dts) : (uint32_t)RAD_BF16;
const uint32_t D = dt == RAD_DT_INVALID ? (uint32_t)RAD_BF16 : dt;
const int64_t n = gi("n", 0);
const int64_t N = gi("N", 0);
const int64_t K = gi("K", 0);
const int64_t group = gi("group", 128);
out->clear();
auto add = [&](uint32_t d, std::vector<int64_t> s, bool idx = false) {
OpdShape o;
o.dtype = d; o.shape = std::move(s); o.is_index = idx;
out->push_back(std::move(o));
};
auto add_fill = [&](uint32_t d, std::vector<int64_t> s, int f, int64_t chunk = 0) {
OpdShape o;
o.dtype = d; o.shape = std::move(s); o.fill = f; o.fill_chunk = chunk;
out->push_back(std::move(o));
};
auto add_idx = [&](std::vector<int64_t> s, int64_t max, int64_t konst = -1,
bool uniq = false) {
OpdShape o;
o.dtype = (uint32_t)RAD_I32; o.shape = std::move(s); o.is_index = true;
o.idx_max = max; o.idx_const = konst; o.idx_unique = uniq;
out->push_back(std::move(o));
};
/* One optional operand this case does not pass. See OpdShape::absent. */
auto skip_opd = [&]() { OpdShape o; o.absent = true; out->push_back(std::move(o)); };
const int64_t head_dim = gi("head_dim", 0);
const int64_t n_head = gi("n_head", 0);
const int64_t n_head_kv = gi("n_head_kv", n_head);
if (op == "rmsnorm") { add(D, {M, n}); add(D, {n}); add(D, {M, n}); }
else if (op == "l2_norm" || op == "softplus") { add(D, {M, n}); add(D, {M, n}); }
else if (op == "rope" || op == "rope_multi") {
/* One inout operand plus positions. qkv is the fused row: n_head queries and n_head_kv
* each of k and v, all head_dim wide. */
if (head_dim <= 0 || n_head <= 0) return RAD_E_UNSUPPORTED;
add(D, {M, (n_head + 2 * n_head_kv) * head_dim});
add((uint32_t)RAD_I32, {M}, true);
}
else if (op == "rmsnorm_add") { add(D, {M, n}); add(D, {M, n}); add(D, {n});
add(D, {M, n}); add(D, {M, n}); }
else if (op == "layernorm") { add(D, {M, n}); add(D, {n}); add(D, {n}); add(D, {M, n}); }
else if (op == "add" || op == "mul") { add(D, {M, n}); add(D, {M, n}); add(D, {M, n}); }
else if (op == "silu_mul") { add(D, {M, 2 * n}); add(D, {M, n}); }
else if (op == "gelu" || op == "silu" || op == "sigmoid") { add(D, {M, n}); add(D, {M, n}); }
else if (op == "softmax") { add(D, {M, n}); add(D, {M, n}); }
else if (op == "gather_rows") {
/* x is a buffer of many rows and idx picks M of them. Sized at 4M rows so the gather is
* not the identity -- the identity is the one case that passes while broken. */
add(D, {4 * M, n}); add((uint32_t)RAD_I32, {M}, true); add(D, {M, n});
}
else if (op == "cast") {
const uint32_t from = rad_dtype_parse(g.get_s("from") ? g.get_s("from") : "f32");
const uint32_t to = rad_dtype_parse(g.get_s("to") ? g.get_s("to") : "f32");
add(from ? from : (uint32_t)RAD_F32, {M, n});
add(to ? to : (uint32_t)RAD_F32, {M, n});
}
else if (op == "gemm_nt") { add(D, {M, K}); add(D, {N, K}); add(D, {M, N}); }
else if (op == "gemm_nt_bias") { add(D, {M, K}); add(D, {N, K}); add(D, {N}); add(D, {M, N}); }
else if (op == "embed_lookup") {
add((uint32_t)RAD_I32, {M}, true);
add(D, {gi("n_vocab", 0), gi("n_embd", 0)});
add(D, {M, gi("n_embd", 0)});
}
else if (op == "logits_gemm") {
add(D, {M, gi("n_embd", 0)});
add(D, {gi("n_vocab", 0), gi("n_embd", 0)});
add((uint32_t)RAD_F32, {M, gi("n_vocab", 0)});
}
else if (op == "quant_act_i8" || op == "had_quant_act_i8") {
add(D, {M, n}); add((uint32_t)RAD_I8, {M, n});
add((uint32_t)RAD_F32, {M, group ? n / group : 1});
/* quant_act_i8 alone carries the optional `asum` output, and it is not passed here --
* see OpdShape::absent. had_quant_act_i8's schema stops at the scale. */
if (op == "quant_act_i8") skip_opd();
}
else if (op == "quant_act_fp8") {
/* The same three operands as quant_act_i8 at a different output width. `dtype` names the
* INPUT, which is bf16; the output width is what the op name says. */
if (n <= 0 || group <= 0) return RAD_E_UNSUPPORTED;
add(D, {M, n});
add((uint32_t)RAD_F8E4M3, {M, n});
add((uint32_t)RAD_F32, {M, (n + group - 1) / group});
}
else if (op == "gemm_nt_q") {
/* BLOCK-SCALED FP8 ONLY, and the restriction is the honest one rather than laziness.
*
* `gemm_nt_q` is one op over six weight formats and the SCALE GRID is what differs between
* them -- per row, per row-group, per output-row-block, an e8m0 exponent byte, with or
* without a zero point or a reference exponent. Every one of those is a property of the
* kernel that reads it, not of the schema, so a recipe that guessed would be testing the
* bounds handling of five kernels and calling the result correctness (see the header).
*
* The fp8 family is different: its grid is stated by the CHECKPOINT -- E4M3 [N][K] against
* a bf16 [ceil(N/128)][ceil(K/128)] plane, with `group` carrying the 128 -- so there is
* nothing left to guess, and it is the family the production model runs on. The rest are
* skipped and counted.
*
* `a_sum` and `b_ref` belong to the asymmetric-integer and mxfp4 grids and are absent. */
const char* q = g.get_s("dtype");
/* OCP-MXFP4 is the other grid: e2m1 codes with one E8M0 exponent per 32 of K (`group`
* 32), read against the fp8 family's own activation pair -- E4M3 with an f32 scale per
* (row, 128 of K), which is what LinearFP8 feeds it. The weight operands arrive in libr4d's
* stored layout, and their BYTE COUNTS are what is sized here: the codes are K/2 bytes a
* row in fragment order, the exponents [K/32][N] and the per-row reference [N]. Drawn
* bytes are fine for timing -- the kernel's work does not depend on which exponents it
* folds. */
if (q && std::strcmp(q, "mxfp4a8") == 0) {
if (N <= 0 || K <= 0 || group != 32) return RAD_E_UNSUPPORTED;
add((uint32_t)RAD_F8E4M3, {M, K});
add((uint32_t)RAD_F32, {M, (K + 127) / 128});
add((uint32_t)RAD_U8, {N, K / 2}); /* b -- e2m1 codes, fragment order */
add((uint32_t)RAD_U8, {K / 32, N}); /* b_scale -- E8M0, [K/32][N] */
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 {
const bool a8 = q && std::strcmp(q, "fp8a8") == 0;
const bool a16 = q && std::strcmp(q, "fp8a16") == 0;
if ((!a8 && !a16) || N <= 0 || K <= 0 || group <= 0) return RAD_E_UNSUPPORTED;
const int64_t kb = (K + group - 1) / group;
const int64_t nb = (N + group - 1) / group;
/* a, a_scale */
if (a8) { add((uint32_t)RAD_F8E4M3, {M, K}); add((uint32_t)RAD_F32, {M, kb}); }
else { add((uint32_t)RAD_BF16, {M, K}); skip_opd(); }
add((uint32_t)RAD_F8E4M3, {N, K}); /* b -- the checkpoint's own bytes */
add((uint32_t)RAD_BF16, {nb, kb}); /* b_scale -- weight_scale_inv, one per 128x128 */
add((uint32_t)RAD_BF16, {M, N}); /* y */
skip_opd(); /* a_sum */
skip_opd(); /* b_ref */
}
}
else if (op == "dequant") {
add((uint32_t)RAD_I8, {M, n}); add((uint32_t)RAD_F32, {M, group ? n / group : 1});
add(D, {M, n});
}
else if (op == "all_reduce" || op == "all_gather") {
/* Both take two operands. all_gather's second is [world_size * numel]; all_reduce's is the
* optional SECOND DESTINATION -- absent means in place, the form docs/OPS.md draws and
* every block issues. It is passed so the out-of-place form is exercised too. */
const int64_t numel = gi("numel", n ? n : M);
add(D, {numel});
add(D, {op == "all_gather" ? numel * gi("world_size", 1) : numel});
}
/* ---- the paged pair. They share one layout and it is stated once for the whole project in
* libref/ref_ops.h:
*
* kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim] K first, V second in a slot
*
* Without a recipe here the attention kernel and the KV scatter -- the pair the whole cache
* design rests on -- cannot be compared against the oracle on real bytes at all. The extents
* they need beyond the parameters are a block COUNT and a context length, and both are this
* tool's to choose rather than the model's: any cache big enough for the case will do, so long
* as the indices land inside it. */
else if (op == "kv_store") {
const int64_t bs = gi("block_size", 0);
const int64_t kvh = gi("n_head_kv", 0);
if (bs <= 0 || kvh <= 0 || head_dim <= 0) return RAD_E_UNSUPPORTED;
/* Two blocks of slack so the slot mapping is not a dense prefix: a scatter that only ever
* writes block 0 agrees with anything about the block index. */
const int64_t nb = (M + bs - 1) / bs + 2;
/* Only the cache takes `kv_dtype`: k and v are bf16 whatever the cache stores, and D,
* which falls back on kv_dtype for an op with no `dtype`, would make them fp8 too. */
const char* kvs = g.get_s("kv_dtype");
const uint32_t kvd = kvs ? rad_dtype_parse(kvs) : (uint32_t)RAD_DT_INVALID;
add((uint32_t)RAD_BF16, {M, kvh, head_dim});
add((uint32_t)RAD_BF16, {M, kvh, head_dim});
add_idx({M}, nb * bs, -1, /*uniq*/ true);
add(kvd == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_BF16 : kvd, {nb, kvh, bs, 2 * head_dim});
}
else if (op == "attn_paged") {
/* `M` is q_len here -- the ranged parameter is the query length and not a token count,
* because one query row at decode and thousands in a prefill chunk are different kernels
* (docs/OPS.md). One sequence, whose context is exactly this query: a causal attention
* over its own prefix, which is the case a prefill chunk actually runs. */
const int64_t bs = gi("block_size", 16);
const int64_t gqa = gi("gqa", 1);
const int64_t nh = gi("n_head", gqa);
if (bs <= 0 || gqa <= 0 || nh <= 0 || head_dim <= 0 || nh % gqa) return RAD_E_UNSUPPORTED;
const int64_t kvh = nh / gqa;
const int64_t n_seq = 1, ctx = M;
const int64_t max_blocks = (ctx + bs - 1) / bs;
add(D, {n_seq * M, nh, head_dim});
add(D, {max_blocks, kvh, bs, 2 * head_dim});
add_idx({n_seq, max_blocks}, max_blocks);
/* NOT a draw: a context shorter than the query makes causal attention read a prefix that
* does not exist, and both implementations would agree about the garbage. */
add_idx({n_seq}, 0, ctx);
skip_opd(); /* k_descale -- this cache is not quantised */
skip_opd(); /* v_descale */
add(D, {n_seq * M, nh, head_dim});
}
/* ---- gated delta net. The layouts are libref/ref_gdn.cpp's, stated there once:
*
* q, k [T, Hk, head_k] v, o [T, Hv, head_v]
* g, beta [T, Hv] fp32 A [T, Hv, chunk]
* h0, ht [N, Hv, head_v, head_k] fp32 cu [N+1]
* conv w [conv_dim, conv_width] conv_state [n_slots, conv_dim, state_len]
*
* with conv_dim = 2 * Hk * head_k + Hv * head_v.
*
* THE HEAD COUNTS ARE NOT PARAMETERS of any of these ops -- the kernels read them off the
* operands -- so they come from the container's metadata through `ctx`. Without them a recipe
* would have to invent a head count, and a GDN check at the wrong head ratio is a check of a
* model nobody is running. `ctx` absent means the caller could not supply them, and the op is
* skipped rather than guessed at, which is this file's rule everywhere else. */
else if (op.rfind("gdn_", 0) == 0 && op != "gdn_gated_rmsnorm") {
if (!ctx || ctx->n_head_k <= 0 || ctx->n_head_v <= 0) return RAD_E_UNSUPPORTED;
const int64_t Hk = ctx->n_head_k, Hv = ctx->n_head_v;
const int64_t hk = gi("head_k", 0), hv = gi("head_v", hk);
const int64_t chunk = gi("chunk", 64);
const int64_t width = gi("conv_width", 4);
if (hk <= 0 || hv <= 0 || chunk <= 0 || width <= 1) return RAD_E_UNSUPPORTED;
const int64_t conv_dim = 2 * Hk * hk + Hv * hv;
const int64_t S = ctx->n_seq > 0 ? ctx->n_seq : 1;
if (op == "gdn_conv_prep") {
/* T tokens over S sequences, one conv-state slot each. `state_len` is the manager's
* conv_width - 1 + n_spec; with no speculation that is conv_width - 1, and the kernel
* reads its window at the slot the last committed token left. */
add(D, {M, conv_dim}); /* x -- the fused projection row */
add(D, {conv_dim, width}); /* w */
skip_opd(); /* b -- this checkpoint has no conv bias */
add((uint32_t)RAD_F32, {Hv}); /* A_log */
add((uint32_t)RAD_F32, {Hv}); /* dt_bias */
add(D, {S, conv_dim, width - 1}); /* conv_state, INOUT */
add_idx({S + 1}, 0, -1); /* cu -- filled cumulative below */
out->back().idx_cu = true;
add(D, {M, Hv}); /* a */
add(D, {M, Hv}); /* b_gate */
add_idx({S}, S, -1, /*uniq*/ true); /* cache_idx -- one slot a sequence */
add_idx({S}, 0, 0); /* has_init -- a cold prefill, SAID rather
* than left absent: ref reads a null as WARM
* and libr4d as COLD, so the default is the
* one thing the two do not share. */
add(D, {M, Hk, hk}); /* q */
add(D, {M, Hk, hk}); /* k */
add(D, {M, Hv, hv}); /* v */
add_fill((uint32_t)RAD_F32, {M, Hv}, OpdShape::FillGateCumsum, chunk); /* g */
add_fill((uint32_t)RAD_F32, {M, Hv}, OpdShape::FillSigmoid); /* beta */
}
else if (op == "gdn_kkt_solve") {
add(D, {M, Hk, hk}); /* k */
add_fill((uint32_t)RAD_F32, {M, Hv}, OpdShape::FillSigmoid); /* beta */
add_fill((uint32_t)RAD_F32, {M, Hv}, OpdShape::FillGateCumsum, chunk); /* g */
add_idx({S + 1}, 0, -1); /* cu */
out->back().idx_cu = true;
add_fill(D, {M, Hv, chunk}, OpdShape::FillTriLower, chunk); /* A */
}
else if (op == "gdn_chunk_scan") {
add(D, {M, Hk, hk}); /* q */
add(D, {M, Hk, hk}); /* k */
add(D, {M, Hv, hv}); /* v */
add_fill(D, {M, Hv, chunk}, OpdShape::FillTriLower, chunk); /* A */
add_fill((uint32_t)RAD_F32, {M, Hv}, OpdShape::FillGateCumsum, chunk); /* g */
add_fill((uint32_t)RAD_F32, {M, Hv}, OpdShape::FillSigmoid); /* beta */
add((uint32_t)RAD_F32, {S, Hv, hv, hk}); /* h0 */
add_idx({S + 1}, 0, -1); /* cu */
out->back().idx_cu = true;
add(D, {M, Hv, hv}); /* o */
add((uint32_t)RAD_F32, {S, Hv, hv, hk}); /* ht */
add_idx({S}, S, -1, /*uniq*/ true); /* state_idx */
}
else if (op == "gdn_conv_update") {
/* The decode pair. `M` is q_len here, one row per candidate token, and the window is
* conv_width - 2 + q_len deep so a rejection is a change of read offset rather than a
* recompute (ref_ops.h's rollback contract). num_accepted is 1-based and all ones is
* the non-speculative decode. */
const int64_t sl = width - 2 + M;
add(D, {S * M, conv_dim}); /* x */
add(D, {conv_dim, width}); /* w */
skip_opd(); /* b */
add(D, {S, conv_dim, sl}); /* conv_state, INOUT */
add_idx({S, M}, S, -1); /* state_idx */
add_idx({S}, 0, 1); /* num_accepted -- none rejected */
add_idx({S + 1}, 0, -1); /* cu */
out->back().idx_cu = true;
add(D, {S * M, Hk, hk}); /* q */
add(D, {S * M, Hk, hk}); /* k */
add(D, {S * M, Hv, hv}); /* v */
}
else if (op == "gdn_recurrent_update") {
add(D, {S * M, Hk, hk}); /* q */
add(D, {S * M, Hk, hk}); /* k */
add(D, {S * M, Hv, hv}); /* v */
add(D, {S * M, Hv}); /* a */
add(D, {S * M, Hv}); /* b */
add((uint32_t)RAD_F32, {Hv}); /* A_log */
add((uint32_t)RAD_F32, {Hv}); /* dt_bias */
add((uint32_t)RAD_F32, {S * M, Hv, hv, hk}); /* state, one per candidate token */
add_idx({S, M}, S * M, -1, /*uniq*/ true); /* state_idx */
add_idx({S}, 0, 1); /* num_accepted */
add_idx({S + 1}, 0, -1); /* cu */
out->back().idx_cu = true;
add(D, {S * M, Hv, hv}); /* z */
add((uint32_t)RAD_F32, {hv}); /* norm_w */
add(D, {S * M, Hv, hv}); /* o */
}
else return RAD_E_UNSUPPORTED;
}
else if (op == "gdn_gated_rmsnorm") {
/* One row per (token, head): `M` is already tokens x heads and `channels` is head_v. */
const int64_t ch = gi("channels", 0);
if (ch <= 0) return RAD_E_UNSUPPORTED;
add(D, {M, ch}); add(D, {M, ch}); add((uint32_t)RAD_F32, {ch}); add(D, {M, ch});
}
/* Deliberately absent, and this is the argument for RadShapeFn rather than an oversight:
* ssm_conv and qk_norm_rope_gate take operands whose extents come from the KV group's state
* geometry and from INTERLEAVED strided views -- attn_q is [n_embd, 2*head_dim*n_head] with
* query and gate alternating per head, so it is not a contiguous split and a recipe here would
* have to know that. The kernel already does. Without the kernel's hook these are skipped and
* counted by the caller, which is the honest outcome: a tool that invents an extent tests the
* kernel's bounds handling and calls it correctness. */
else return RAD_E_UNSUPPORTED;
if ((int)out->size() != n_opd) {
/* The recipe and the schema disagree. That is a bug in one of them, and padding with a
* guess would hide it behind a number that looks like a result. */
RAD_DEBUG("%s: shape recipe produces %zu operands, the schema declares %d",
op.c_str(), out->size(), n_opd);
return RAD_E_UNSUPPORTED;
}
for (const OpdShape& s : *out)
for (int64_t d : s.shape)
if (d <= 0) return RAD_E_UNSUPPORTED;
return RAD_OK;
}
int rad_operand_shapes(const std::string& op, const Geometry& g, int n_opd, int64_t M,
std::vector<OpdShape>* out, const ShapeCtx* ctx = nullptr);
inline int64_t rad_numel(const std::vector<int64_t>& s) {
int64_t n = 1;
@@ -495,9 +89,8 @@ inline int64_t rad_numel(const std::vector<int64_t>& s) {
return n;
}
/* Everything is materialised in f32 for comparison and for filling. A kernel writing bf16 is
* compared after widening: two implementations disagreeing in the last bf16 bit is what a
* tolerance is for, and comparing raw uint16 would make every such case a failure. */
/* Values are materialised in f32 for filling and comparison; narrow outputs are widened first, so
* a last-bit bf16 difference falls within tolerance. */
void rad_widen (const void* src, uint32_t dtype, int64_t n, std::vector<float>* out);
void rad_narrow(const float* src, uint32_t dtype, int64_t n, void* dst);
@@ -510,10 +103,13 @@ inline uint64_t rad_splitmix(uint64_t& x) {
}
uint64_t rad_case_seed(uint64_t base, std::string_view op, int band, int domain, int operand);
void rad_fill_normal(float* p, int64_t n, uint64_t seed, float sigma);
/* THE BLOCK WIDTH IS PART OF THE CONTRACT, not an implementation detail: a caller that streams a
* large operand block by block must use the same width rad_fill_normal splits at, or the two
* produce different values for the same seed. */
/* The block width is part of the contract: a caller streaming an operand block by block must use
* the width rad_fill_normal splits at, or the same seed gives different values. */
extern const int64_t RAD_FILL_BLOCK;
void rad_fill_normal_block(float* p, int64_t n, uint64_t seed, int64_t block, float sigma);
/* Runs fn(b) for each block b in [0, nb), round-robin over the hardware threads. A block's result
* must not depend on which thread runs it. */
void rad_for_blocks(int64_t nb, const std::function<void(int64_t)>& fn);
} /* namespace rad */
+4 -4
View File
@@ -1,14 +1,14 @@
#!/usr/bin/env python3
"""pad_tp.py — pad a Llama/Qwen-style HF safetensors checkpoint to a geometry that divides by a
tensor-parallel world size, with ZERO weights, so the padded model computes exactly what the
tensor-parallel world size, with zero weights, so the padded model computes exactly what the
original does.
pad_tp.py SRC DST --heads 36 --kv-heads 9 [--ff 8448] [--gdn-k 18 --gdn-v 54]
What is padded and why it is exact (fp32-accumulated, zero terms add nothing):
attention k_proj / v_proj gain zero ROWS (new kv heads); q_proj gains zero rows so every kv
attention k_proj / v_proj gain zero rows (new kv heads); q_proj gains zero rows so every kv
group has the new ratio gqa' = heads'/kv_heads' -- a group that existed keeps its real
q heads first, then zero q heads; a new group is all zero. o_proj gains zero COLUMNS
q heads first, then zero q heads; a new group is all zero. o_proj gains zero columns
in the same head order. A zero q head attends uniformly, but its o_proj column is
zero, so it contributes 0; a zero kv head stores zeros, read only by zero q heads.
mlp gate_proj / up_proj gain zero rows, down_proj zero columns: silu(0)*0 = 0.
@@ -175,7 +175,7 @@ def main():
else:
st_write_stream(os.path.join(a.dst, fn), meta, items); print(f" wrote {fn} ({len(items)} tensors)", flush=True)
if a.sparse:
# new shards, ~2 GB each, named to sort BEFORE every original ("model-00000-…" < "model-00001-…")
# new shards, ~2 GB each, named to sort before every original ("model-00000-…" < "model-00001-…")
CH = 2 << 30; chunks = [[]]; acc = 0
for it in sparse_items:
if acc + it[3] > CH and chunks[-1]: chunks.append([]); acc = 0
+1 -1
View File
@@ -3,7 +3,7 @@
pad_verify.py SRC PADDED
Re-derives the head/row maps from PADDED/config.json `_tp_padding`, then for EVERY tensor in the
Re-derives the head/row maps from PADDED/config.json `_tp_padding`, then for every tensor in the
padded index checks, streaming one tensor at a time:
untouched tensors byte-identical to the source
padded tensors every real row/column block equals the source block it came from, and every
+659
View File
@@ -0,0 +1,659 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""rad-export -- a finetune's output to a .rad, encoded by the model's own recipe.
A LoRA trainer (Unsloth, PEFT/TRL, Axolotl, a plain torch loop) leaves either a merged 16-bit
checkpoint or a LoRA adapter. rad-convert takes the first and a recipe; the tuned container should
be encoded exactly like the stock one, so the recipe is the one the stock model is converted with.
rad-export does the steps between:
1. a LoRA adapter is folded into its base as PEFT's merge_and_unload folds it on the CPU,
W' = W + scale * B @ A, written tensor by tensor into ~1 GiB shards beside the output (peak
RAM a few GiB, not the model twice);
2. the recipe is picked (by name, a file, or `auto` from the checkpoint's base model) and its
header's usage line supplies the --set keys and whether a drafter (--draft-model) is needed;
3. the drafter is found: --draft, the config file, or the Hub repository the recipe's usage line
names (the local Hub cache, else downloaded with huggingface_hub);
4. rad-convert runs -- the installed one, or the one in the Radiance image under docker with no
network (CPU only: a convert never opens a GPU, so it is safe beside a running serve).
rad-export SRC [-o OUT.rad] [--recipe NAME|FILE|auto] [--base DIR] [--draft DIR|ORG/NAME]
[--set K=V ...] [--image IMAGE | --rad-convert PATH] [--dry-run] [-- rad-convert args]
rad-export --list-recipes [--json] [--image IMAGE | --rad-convert PATH]
SRC is a merged checkpoint (config.json + *.safetensors) or a PEFT adapter (adapter_config.json +
adapter_model.safetensors). OUT defaults to SRC's folder name + .rad beside SRC (or in out_dir).
Optional config ~/.config/rad-export/config.json (or --config):
{"image": "stilldeadcode/radiance", "out_dir": "/models/rad",
"recipes": {"Qwen3.8-27B": "q38-27b-fp8block-df2"}, # base-model substring -> recipe
"drafts": {"q38-27b-fp8block-df2": "/models/Qwen3.8-27B-DFlash2"}, # recipe -> drafter
"bases": {"Qwen/Qwen3.8-27B": "/models/Qwen3.8-27B"}, # adapter base id -> local copy
"hub_cache": ["~/.cache/huggingface/hub"]}
Run from an Unsloth Studio post-export hook (UNSLOTH_POST_EXPORT set), the last line names the .rad
as UNSLOTH_HOOK_OUTPUT=<path> so Studio lists it with the export.
"""
import argparse, glob, json, math, os, re, shlex, shutil, struct, subprocess, sys, tempfile, time
IMAGE_RECIPES = "/opt/radiance/share/radiance/recipes"
DEFAULT_IMAGE = "stilldeadcode/radiance"
SHARD = 1 << 30
# What a conversion reads from a Hub repository; anything else (.bin, .gguf, .pth copies) is not
# downloaded.
HUB_FILES = ["*.json", "*.safetensors", "*.jinja", "*.model", "*.tiktoken", "*.txt"]
# Weight files that are not copied from a base into the merged checkpoint.
WEIGHT_EXT = (".safetensors", ".bin", ".pt", ".pth", ".ckpt", ".gguf", ".h5", ".msgpack", ".onnx",
".npz")
# The tokenizer and chat-template files an adapter may carry; the trainer's copies replace the
# base's in the merged checkpoint.
TOKENIZER_FILES = ("tokenizer.json", "tokenizer_config.json", "special_tokens_map.json",
"added_tokens.json", "chat_template.jinja", "chat_template.json", "tokenizer.model",
"vocab.json", "merges.txt")
HUB_ID = re.compile(r"[A-Za-z0-9][\w.-]*/[A-Za-z0-9][\w.-]*")
def die(msg, code=1):
print(f"rad-export: {msg}", file=sys.stderr)
sys.exit(code)
def say(msg):
print(f"rad-export: {msg}", flush=True)
def hub_id(s):
"""`s` when it is an ORG/NAME Hub repository id, else None. Ids come from files this tool did
not write (an adapter's config, a recipe header), so they are checked before they become a
cache path or a download."""
s = str(s or "")
return s if HUB_ID.fullmatch(s) and ".." not in s else None
# ---------------------------------------------------------------- recipes
class Backend:
"""Where rad-convert runs and where its recipes are: the installed tool, or the image under docker."""
def __init__(self, a, cfg):
self.native = a.rad_convert or (None if a.image else shutil.which("rad-convert"))
self.image = a.image or os.environ.get("RADIANCE_IMAGE") or cfg.get("image") or DEFAULT_IMAGE
self.memory = a.memory
self._dir = a.recipes_dir
def docker(self):
if not shutil.which("docker"):
die("no rad-convert on PATH and no docker to run the image's; pass --rad-convert PATH")
return "docker"
def recipes_dir(self):
if self._dir:
return self._dir
if self.native:
prefix = os.path.dirname(os.path.dirname(os.path.realpath(self.native)))
for d in (os.path.join(prefix, "share", "radiance", "recipes"),
os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "data", "recipes")):
if os.path.isdir(d):
self._dir = os.path.realpath(d)
return self._dir
die(f"no recipes next to {self.native}; pass --recipes-dir")
# the image's own recipes, copied out once per image id
dk = self.docker()
iid = subprocess.run([dk, "image", "inspect", "-f", "{{.Id}}", self.image], capture_output=True, text=True)
if iid.returncode != 0:
die(f"docker image {self.image} not found (docker pull {self.image}, or --image / --rad-convert)")
cache = os.path.join(os.path.expanduser("~/.cache/rad-export"), "recipes-" + iid.stdout.strip().split(":")[-1][:16])
if not os.path.isdir(cache):
os.makedirs(os.path.dirname(cache), exist_ok=True)
tmp = tempfile.mkdtemp(prefix=".recipes-", dir=os.path.dirname(cache))
cid = subprocess.run([dk, "create", self.image], capture_output=True, text=True, check=True).stdout.strip()
try:
subprocess.run([dk, "cp", f"{cid}:{IMAGE_RECIPES}", os.path.join(tmp, "r")], check=True, capture_output=True)
try:
os.replace(os.path.join(tmp, "r"), cache)
except OSError:
if not os.path.isdir(cache): # another run put it there first
raise
finally:
subprocess.run([dk, "rm", cid], capture_output=True)
shutil.rmtree(tmp, ignore_errors=True)
self._dir = cache
return cache
def recipe_path_for_convert(self, local_path):
"""The path rad-convert sees: the same file inside the image when it is one of the image's recipes."""
if not self.native and os.path.dirname(local_path) == self.recipes_dir():
return os.path.join(IMAGE_RECIPES, os.path.basename(local_path))
return local_path
def command(self, args, mounts):
"""The rad-convert command line. Under docker the container runs as the caller, with no
network and no pull, and sees only `mounts` (path -> read-only), each at its own path."""
if self.native:
return [self.native] + args
cmd = [self.docker(), "run", "--rm", "--pull", "never", "--network", "none",
"-u", f"{os.getuid()}:{os.getgid()}"]
if self.memory:
cmd += ["--memory", self.memory]
roots = {}
for path, ro in mounts.items():
# a Hub cache snapshot is symlinks into ../../blobs: mount the whole repository folder
root = path.split("/snapshots/")[0] if "/snapshots/" in path else path
roots[root] = roots.get(root, True) and ro
for path, ro in sorted(roots.items()):
if any(c in path for c in ',"\n'):
die(f"cannot mount {path!r} into the container (a comma, quote or newline in the path)")
cmd += ["--mount", f"type=bind,src={path},dst={path}" + (",readonly" if ro else "")]
return cmd + ["--entrypoint", "/opt/radiance/bin/rad-convert", self.image] + args
def run(self, args, mounts, log):
"""Run the convert with its output going to `log`; returns the exit code."""
with open(log, "w") as f:
return subprocess.run(self.command(args, mounts), stdout=f, stderr=subprocess.STDOUT).returncode
def read_recipe(path):
"""Header facts: the summary line, whether calibration data is needed, and the usage line's flags."""
text = open(path, encoding="utf-8").read()
header = []
for line in text.splitlines():
if not line.startswith("#"):
break
header.append(line[1:].strip())
summary = header[0].split("--", 1)[-1].strip() if header else ""
usage, on = [], False
for h in header:
if h.startswith("rad-convert"):
on = True
if on:
usage.append(h.rstrip("\\").strip())
if not h.endswith("\\"):
break
flags = {"draft": None, "set": []}
toks = shlex.split(" ".join(usage)) if usage else []
for i, t in enumerate(toks):
if t == "--draft-model" and i + 1 < len(toks):
flags["draft"] = toks[i + 1].strip("<>")
if t == "--set" and i + 1 < len(toks):
flags["set"].append(toks[i + 1])
calib = bool(re.search(r"\$CALIB\b|calib=\$|--imatrix", text))
return {"name": os.path.basename(path)[:-7], "summary": " ".join(header[:3]), "first": summary, "calib": calib, **flags}
def list_recipes(backend):
d = backend.recipes_dir()
return [read_recipe(p) for p in sorted(glob.glob(os.path.join(d, "*.recipe")))]
# ---------------------------------------------------------------- checkpoint facts
def read_json(path, strict=False):
"""A JSON file's object; {} when it is absent, or (unless `strict`) unreadable."""
if not os.path.exists(path):
return {}
try:
v = json.load(open(path, encoding="utf-8-sig"))
except Exception as e:
if strict:
die(f"{path}: {e}")
return {}
if not isinstance(v, dict):
if strict:
die(f"{path}: not a JSON object")
return {}
return v
def st_header(path):
"""A safetensors file's tensors, name -> (dtype, shape), from its header alone."""
with open(path, "rb") as f:
raw = f.read(8)
if len(raw) != 8:
die(f"{path}: not a safetensors file")
n = struct.unpack("<Q", raw)[0]
if n > (100 << 20):
die(f"{path}: a safetensors header of {n} bytes")
try:
h = json.loads(f.read(n))
except Exception as e:
die(f"{path}: unreadable safetensors header: {e}")
return {k: (v["dtype"], list(v["shape"])) for k, v in h.items() if k != "__metadata__"}
def weight_files(d):
"""The checkpoint's shards and the tensors each holds: the index's assignment when there is one
(a shard on disk that the index does not name is not read), else every *.safetensors."""
idx = read_json(os.path.join(d, "model.safetensors.index.json"), strict=True).get("weight_map")
if idx:
out = {}
for k, f in idx.items():
out.setdefault(f, []).append(k)
return out
out, seen = {}, {}
for p in sorted(glob.glob(os.path.join(d, "*.safetensors"))):
f = os.path.basename(p)
out[f] = list(st_header(p))
for k in out[f]:
if k in seen:
die(f"{d}: tensor {k} is in both {seen[k]} and {f}, and no index says which to read")
seen[k] = f
return out
def base_model_of(src):
for name, key in (("export_metadata.json", "base_model"), ("adapter_config.json", "base_model_name_or_path"), ("config.json", "_name_or_path")):
v = read_json(os.path.join(src, name)).get(key)
if v:
return str(v)
return ""
def model_names(src, base):
"""Names to match recipes against: the base model id and its last path component, and the base's own."""
out = []
for v in (base_model_of(src), base and read_json(os.path.join(base, "config.json")).get("_name_or_path"), base):
if v:
out += [str(v), os.path.basename(str(v).rstrip("/"))]
return [n for n in dict.fromkeys(out) if n]
def complete(d):
"""A checkpoint folder with every weight file present (a Hub snapshot mid-download has config.json first)."""
if not os.path.exists(os.path.join(d, "config.json")):
return False
idx = read_json(os.path.join(d, "model.safetensors.index.json")).get("weight_map")
if idx:
return all(os.path.exists(os.path.join(d, f)) for f in set(idx.values()))
return any(os.path.exists(p) for p in glob.glob(os.path.join(d, "*.safetensors")))
def hub_snapshot(repo, cache_dirs):
if not hub_id(repo):
return None
org, _, name = repo.partition("/")
snaps = [s for c in cache_dirs for s in glob.glob(os.path.join(glob.escape(os.path.expanduser(c)),
f"models--{glob.escape(org)}--{glob.escape(name)}",
"snapshots", "*"))
if complete(s)]
return max(snaps, key=os.path.getmtime) if snaps else None
def hub_fetch(repo, cache_dirs, dry):
if not hub_id(repo):
return None
path = hub_snapshot(repo, cache_dirs)
if path:
return path
if dry:
return f"<would download {repo}>"
try:
from huggingface_hub import snapshot_download
except ImportError:
return None
say(f"downloading {repo} from the Hugging Face Hub ({', '.join(HUB_FILES)})")
try:
return snapshot_download(repo, allow_patterns=HUB_FILES)
except Exception as e:
say(f"{repo}: {e}")
return None
def checkpoint_dir(path, what, dry):
"""`path` when it is a complete checkpoint folder; refused with `what` otherwise."""
if dry and path.startswith("<would download"):
return path
if not complete(path):
die(f"{what} {path} is not a checkpoint (config.json and every *.safetensors shard)")
return os.path.realpath(path)
def resolve_base(base_id, a, cfg):
hub = cfg.get("hub_cache", ["~/.cache/huggingface/hub"])
if a.base:
return checkpoint_dir(a.base, "--base", a.dry_run)
pinned = cfg.get("bases", {}).get(base_id)
if pinned:
return checkpoint_dir(os.path.expanduser(pinned), "the config's base", a.dry_run)
if base_id and os.path.isdir(base_id):
return checkpoint_dir(base_id, "the adapter's base", a.dry_run)
if hub_id(base_id):
p = hub_fetch(base_id, hub, a.dry_run)
return checkpoint_dir(p, "the adapter's base", a.dry_run) if p else None
return None
def pick_recipe(a, cfg, recipes, names):
if a.recipe and a.recipe != "auto":
if os.path.isfile(a.recipe):
return read_recipe(os.path.realpath(a.recipe)), os.path.realpath(a.recipe)
byname = {r["name"]: r for r in recipes}
name = a.recipe[:-7] if a.recipe.endswith(".recipe") else a.recipe
if name not in byname:
die(f"no recipe '{name}' (--list-recipes shows them)")
return byname[name], None
for key, rname in cfg.get("recipes", {}).items():
if any(key.lower() in n.lower() for n in names):
return pick_recipe(argparse.Namespace(recipe=rname), {}, recipes, names)
# auto: recipes whose header names this model, take a bf16 checkpoint, and need no calibration data
cands = [r for r in recipes if not r["calib"] and any(n.lower() in r["summary"].lower() for n in names if len(n) > 3)]
bf16 = [r for r in cands if "bf16" in r["summary"].lower()]
cands = bf16 or cands
if len(cands) == 1:
return cands[0], None
if not cands:
die(f"no recipe names {names[:2]}; pick one with --recipe (rad-export --list-recipes)")
shown = next((n for n in names if not os.path.isdir(n)), os.path.basename(names[0]))
die("several recipes fit " + repr(shown) + ": " + ", ".join(r["name"] for r in cands) +
" -- pick one with --recipe, or pin it in the config's \"recipes\"")
def resolve_draft(a, cfg, recipe, dry):
"""The drafter: --draft, the config's pin for the recipe, or the Hub repository the recipe's
usage line names. A usage line with a placeholder (`<... checkpoint>`) names no repository,
and no name is guessed from it."""
hub = cfg.get("hub_cache", ["~/.cache/huggingface/hub"])
want = recipe.get("draft")
if a.draft:
if os.path.isdir(a.draft):
return checkpoint_dir(a.draft, "--draft", dry)
return hub_fetch(a.draft, hub, dry) or die(f"drafter {a.draft} is neither a folder nor a Hub "
"repository this can fetch")
if not want:
return None
pinned = cfg.get("drafts", {}).get(recipe["name"])
if pinned:
pinned = os.path.expanduser(pinned)
if os.path.isdir(pinned):
return checkpoint_dir(pinned, "the config's drafter", dry)
return hub_fetch(pinned, hub, dry) or die(f"the config's drafter {pinned} is neither a "
"folder nor a Hub repository this can fetch")
path = hub_fetch(want, hub, dry) if hub_id(want) else None
if not path:
die(f"recipe {recipe['name']} merges a drafter ({want}); pass --draft DIR or ORG/NAME, or "
"pin one in the config's \"drafts\"")
return path
def out_stem(src):
"""The .rad's name: SRC's folder, prefixed by its parent's for a trainer's generic folder name
(run-checkpoint-123, not checkpoint-123), without an export-type suffix."""
stem = os.path.basename(src)
if re.fullmatch(r"(adapter|merged|lora|model|final|checkpoint[-_].*)", stem, re.I):
stem = os.path.basename(os.path.dirname(src)) + "-" + stem
return re.sub(r"[-_](adapter|merged|lora)(-16bit)?$", "", stem, flags=re.I) or stem
# ---------------------------------------------------------------- LoRA merge
def pattern_key(patterns, module):
"""PEFT's get_pattern_key: the first rank_pattern / alpha_pattern key that matches the end of
the module name on a dot boundary, or None."""
for k in patterns:
if re.match(rf"(.*\.)?({k})$", module):
return k
return None
def adapter_config(adapter):
cfg = read_json(os.path.join(adapter, "adapter_config.json"), strict=True)
if cfg.get("peft_type", "LORA") != "LORA" or cfg.get("use_dora"):
die("only plain LoRA adapters merge here (DoRA and other PEFT types: merge_and_unload in PEFT, then pass the merged folder)")
if cfg.get("modules_to_save"):
die("adapter has modules_to_save; merge with PEFT's merge_and_unload and pass the merged folder")
if cfg.get("lora_bias"):
die("adapter trains a LoRA bias; merge with PEFT's merge_and_unload and pass the merged folder")
for k in ("r", "lora_alpha"):
v = cfg.get(k)
if isinstance(v, bool) or not isinstance(v, (int, float)) or not v > 0:
die(f"{adapter}/adapter_config.json: {k} is {v!r}, not a positive number")
for k in ("rank_pattern", "alpha_pattern"):
if not isinstance(cfg.get(k) or {}, dict):
die(f"{adapter}/adapter_config.json: {k} is not an object")
return cfg
def scale_of(cfg, module):
"""(r, scale) for one module as PEFT's update_layer sets them: the pattern's r and alpha where
one matches, scale alpha / r, or alpha / sqrt(r) with rsLoRA."""
rp, ap = cfg.get("rank_pattern") or {}, cfg.get("alpha_pattern") or {}
rk, ak = pattern_key(rp, module), pattern_key(ap, module)
r = rp[rk] if rk is not None else cfg["r"]
alpha = ap[ak] if ak is not None else cfg["lora_alpha"]
return r, (alpha / math.sqrt(r) if cfg.get("use_rslora") else alpha / r)
def plan_merge(adapter, base):
"""Check an adapter against its base from the safetensors headers alone, before a tensor is
read: which base weight each A/B pair folds into, with its scale. Anything this cannot merge
exactly is refused."""
cfg = adapter_config(adapter)
wpath = os.path.join(adapter, "adapter_model.safetensors")
if not os.path.exists(wpath):
die(f"{adapter}: no adapter_model.safetensors")
ad = st_header(wpath)
odd = [k for k in ad if not re.search(r"\.lora_[AB]\.(weight|default\.weight)$", k)]
if odd:
die(f"adapter holds tensors other than linear LoRA A/B ({odd[0]}, ...): embedding LoRA, trained biases or "
"saved modules -- merge with PEFT's merge_and_unload and pass the merged folder")
base_shape = {}
for f, ks in weight_files(base).items():
hdr = st_header(os.path.join(base, f))
for k in ks:
if k not in hdr:
die(f"{base}: the index puts {k} in {f}, which does not hold it")
base_shape[k] = hdr[k][1]
fan_in_fan_out = bool(cfg.get("fan_in_fan_out"))
pairs = {}
for k in sorted(ad):
if ".lora_B." in k:
if k.replace(".lora_B.", ".lora_A.") not in ad:
die(f"adapter has {k} without its lora_A")
continue
bk = k.replace(".lora_A.", ".lora_B.")
if bk not in ad:
die(f"adapter has {k} without its lora_B")
module = k.replace("base_model.model.", "", 1).split(".lora_A.")[0]
(_, sa), (_, sb) = ad[k], ad[bk]
r, scale = scale_of(cfg, module)
if len(sa) != 2 or len(sb) != 2:
die(f"{module}: a LoRA of rank-{len(sa)} tensors (a convolution's); merge with PEFT's merge_and_unload")
if sa[0] != r or sb[1] != r:
die(f"{module}: A {sa} and B {sb} are not rank {r}, the rank the adapter config gives it")
key = module + ".weight"
if key not in base_shape:
# VLM checkpoints keep the text model under model.language_model.
alt = key.replace("model.", "model.language_model.", 1)
if alt not in base_shape:
die(f"adapter targets {key}, which the base checkpoint does not have")
key = alt
want = [sa[1], sb[0]] if fan_in_fan_out else [sb[0], sa[1]]
if base_shape[key] != want:
die(f"{key}: the adapter's delta is {want} and the weight {base_shape[key]}")
pairs[key] = (k, bk, scale)
return pairs, fan_in_fan_out
def tokenizer_size(path):
"""The token ids a tokenizer.json can emit: its vocabulary and added tokens, max id + 1."""
tj = read_json(path)
vocab = (tj.get("model") or {}).get("vocab")
n = 0
if isinstance(vocab, dict):
n = max(vocab.values(), default=-1) + 1
elif isinstance(vocab, list):
n = len(vocab)
for t in tj.get("added_tokens") or []:
if isinstance(t.get("id"), int):
n = max(n, t["id"] + 1)
return n
def merge_lora(adapter, base, out):
"""Fold a PEFT LoRA adapter into a copy of the base checkpoint, streaming tensor by tensor.
Each delta is (B @ A) * scale in fp32, transposed for fan_in_fan_out (Conv1D) weights. As in
PEFT's merge on the CPU, a bf16 or fp16 adapter's delta is rounded to the adapter's dtype
before it is added, and the sum is rounded once to the base weight's dtype."""
pairs, fan_in_fan_out = plan_merge(adapter, base)
import torch
from safetensors import safe_open
from safetensors.torch import load_file, save_file
ad = load_file(os.path.join(adapter, "adapter_model.safetensors"))
os.makedirs(out, exist_ok=True)
for f in os.listdir(base):
p = os.path.join(base, f)
if os.path.isfile(p) and not f.endswith(WEIGHT_EXT) and f != "model.safetensors.index.json":
shutil.copy2(p, os.path.join(out, f))
# The trainer's tokenizer and chat template are the tuned model's.
if os.path.exists(os.path.join(adapter, "tokenizer.json")):
bcfg = read_json(os.path.join(base, "config.json"))
rows = bcfg.get("vocab_size") or (bcfg.get("text_config") or {}).get("vocab_size")
n = tokenizer_size(os.path.join(adapter, "tokenizer.json"))
if rows and n > rows:
die(f"the adapter's tokenizer has {n} tokens and the base's embedding {rows} rows; a "
"resized embedding is not merged here -- use PEFT's merge_and_unload")
for f in TOKENIZER_FILES:
if os.path.isfile(os.path.join(adapter, f)):
shutil.copy2(os.path.join(adapter, f), os.path.join(out, f))
files = weight_files(base)
shards, cur, size, wm, total, done, maxrel = 0, {}, 0, {}, 0, 0, 0.0
def flush():
nonlocal shards, cur, size
if cur:
shards += 1
save_file(cur, os.path.join(out, f"part-{shards:05d}.safetensors"), metadata={"format": "pt"})
cur, size = {}, 0
for f in sorted(files):
with safe_open(os.path.join(base, f), "pt") as h:
for k in files[f]:
t = h.get_tensor(k)
if k in pairs:
ka, kb, s = pairs.pop(k)
A, B = ad[ka], ad[kb]
d = (B.float() @ A.float()) * s
if fan_in_fan_out: # GPT-2 style Conv1D weights are stored transposed
d = d.T
if B.dtype in (torch.float16, torch.bfloat16):
d = d.to(B.dtype)
w, d = t.float(), d.float()
wn = w.norm().item()
if wn > 0:
maxrel = max(maxrel, d.norm().item() / wn)
t = (w + d).to(t.dtype)
if not torch.isfinite(t).all():
die(f"{k}: the merged weight is not finite")
done += 1
cur[k] = t.contiguous()
wm[k] = shards + 1
n = t.numel() * t.element_size()
size += n
total += n
if size >= SHARD:
flush()
flush()
for i in range(1, shards + 1):
os.rename(os.path.join(out, f"part-{i:05d}.safetensors"), os.path.join(out, f"model-{i:05d}-of-{shards:05d}.safetensors"))
json.dump({"metadata": {"total_size": total}, "weight_map": {k: f"model-{i:05d}-of-{shards:05d}.safetensors" for k, i in wm.items()}},
open(os.path.join(out, "model.safetensors.index.json"), "w"), indent=1)
say(f"merged {done} LoRA weights into {base} (largest |dW|/|W| {maxrel:.4f})")
# ---------------------------------------------------------------- main
def main():
argv = sys.argv[1:]
extra = []
if "--" in argv:
i = argv.index("--")
argv, extra = argv[:i], argv[i + 1:]
ap = argparse.ArgumentParser(prog="rad-export", description=__doc__.split("\n\n")[0], formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("src", nargs="?", help="merged checkpoint or LoRA adapter folder")
ap.add_argument("-o", "--out", help="the .rad to write")
ap.add_argument("--recipe", default="auto", help="recipe name, recipe file, or auto (default)")
ap.add_argument("--base", help="base checkpoint for a LoRA adapter (default: the adapter's base_model_name_or_path)")
ap.add_argument("--draft", help="drafter folder or Hub id, when the recipe merges one")
ap.add_argument("--set", action="append", default=[], help="extra rad-convert --set K=V (after the recipe's own)")
ap.add_argument("--image", help=f"Radiance image for docker (default $RADIANCE_IMAGE, the config, {DEFAULT_IMAGE})")
ap.add_argument("--rad-convert", help="use this rad-convert binary instead of docker")
ap.add_argument("--recipes-dir", help="recipes folder (default: the installed or image's own)")
ap.add_argument("--memory", help="docker memory limit for the convert, e.g. 24g")
ap.add_argument("--config", default=os.path.expanduser("~/.config/rad-export/config.json"))
ap.add_argument("--list-recipes", action="store_true")
ap.add_argument("--json", action="store_true", help="with --list-recipes: JSON (names first entry 'auto')")
ap.add_argument("--keep-merged", action="store_true", help="keep the merged checkpoint of a LoRA adapter beside OUT")
ap.add_argument("--dry-run", action="store_true", help="resolve everything, print the rad-convert command, convert nothing")
a = ap.parse_args(argv)
cfg = read_json(a.config, strict=True)
be = Backend(a, cfg)
if a.list_recipes:
rs = list_recipes(be)
if a.json:
print(json.dumps({"recipes": ["auto"] + [r["name"] for r in rs if not r["calib"]],
"needs_calibration": [r["name"] for r in rs if r["calib"]]}))
else:
for r in rs:
print(f"{r['name']:34s} {'[calib] ' if r['calib'] else ''}{'[drafter] ' if r['draft'] else ''}{r['first'][:90]}")
return
if not a.src:
ap.error("SRC is required")
src = os.path.realpath(a.src)
adapter = os.path.exists(os.path.join(src, "adapter_config.json"))
if not adapter and not os.path.exists(os.path.join(src, "config.json")):
die(f"{src} is neither a merged checkpoint (config.json) nor a LoRA adapter (adapter_config.json)")
base_id = base_model_of(src)
base = resolve_base(base_id, a, cfg) if adapter else None
if adapter and not base:
die(f"the adapter's base {base_id!r} is neither on this disk nor fetched; pass --base")
names = model_names(src, base)
recipe, recipe_file = pick_recipe(a, cfg, list_recipes(be), names)
recipe_file = recipe_file or os.path.join(be.recipes_dir(), recipe["name"] + ".recipe")
draft = resolve_draft(a, cfg, recipe, a.dry_run)
out = os.path.abspath(a.out) if a.out else os.path.join(
os.path.expanduser(cfg["out_dir"]) if cfg.get("out_dir") else os.path.dirname(src), out_stem(src) + ".rad")
os.makedirs(os.path.dirname(out), exist_ok=True)
say(f"{'adapter' if adapter else 'merged checkpoint'} {src} -> {out}; recipe {recipe['name']}" + (f", drafter {draft}" if draft else ""))
work = tempfile.mkdtemp(prefix=".rad-export-", dir=os.path.dirname(out))
t0 = time.time()
try:
merged = os.path.join(work, "merged") if adapter else src
if adapter and not a.dry_run:
merge_lora(src, base, merged)
args = [merged, "-o", out, "--recipe", be.recipe_path_for_convert(recipe_file)]
# The merged checkpoint carries the adapter's tokenizer where it has one, else the base's.
if any(d and not d.startswith("<") and os.path.exists(os.path.join(d, "tokenizer.json"))
for d in ([src, base] if adapter else [src])):
args += ["--tokenizer", os.path.join(merged, "tokenizer.json")]
if draft:
args += ["--draft-model", draft]
for kv in recipe["set"] + a.set:
args += ["--set", kv]
args += extra
mounts = {os.path.dirname(out): False, os.path.realpath(merged): True}
if draft:
mounts[os.path.realpath(draft)] = True
if not be.recipe_path_for_convert(recipe_file).startswith(IMAGE_RECIPES):
mounts[os.path.dirname(recipe_file)] = True
say("rad-convert " + " ".join(shlex.quote(x) for x in args))
if a.dry_run:
return
log = out + ".log"
rc = be.run(args, mounts, log)
if rc != 0 or not os.path.exists(out) or os.path.getsize(out) == 0:
tail = open(log, errors="replace").read()[-1500:]
die(f"rad-convert failed (exit {rc}); log {log}\n" + tail)
say(f"wrote {out} ({os.path.getsize(out) / 2**30:.2f} GiB) in {time.time() - t0:.0f} s; log {log}")
if a.keep_merged and merged != src:
shutil.move(merged, out + ".merged")
say(f"merged checkpoint kept at {out}.merged")
if os.environ.get("UNSLOTH_POST_EXPORT"):
print(f"UNSLOTH_HOOK_OUTPUT={out}", flush=True)
finally:
shutil.rmtree(work, ignore_errors=True)
if __name__ == "__main__":
main()
+45 -78
View File
@@ -13,35 +13,33 @@
* spellings and the turn terminators; under a fixtures root they are found as
* Qwen3.8-Flash-Next (or Qwen3.8-27B-FP8), Qwen3.6-35B-A3B-FP8 and MiniCPM5-2B.
*
* WHAT THE CTEST SUITE CANNOT DO, and this does. tests/chatparse_test cuts replies at synthetic
* boundaries because the tokenizers are too big to commit. Here every reply is tokenised by the
* model's own tokenizer and decoded token by token through the same Detokenizer, with the same
* preserved control tokens, as the server -- so the parser is fed the pieces it is fed in
* production, split exactly where the model's tokens split them. On every reply:
* Unlike tests/chatparse_test, which cuts replies at synthetic boundaries (the tokenizers are too
* big to commit), every reply here is tokenised by the model's own tokenizer and decoded token by
* token through the server's Detokenizer with the same preserved control tokens, so the parser
* sees production pieces. Per reply it checks:
*
* * the differential verdict against the legacy path (tests/legacy/, "old" in the report;
* chatdiff::judge);
* * the streaming contract at the token boundaries (chatdiff::check_stream);
* * the legacy path's own stream -- the accumulated reply re-parsed at every token, diffed
* against what it had sent -- against its buffered answer, counting where the two disagree.
* * the streaming contract at token boundaries (chatdiff::check_stream);
* * the legacy path's own stream (the reply re-parsed at every token, diffed against what it
* sent) against its buffered answer.
*
* And the cost: a long reply streamed token by token through the SSE layer, legacy ("old")
* against streaming ("new"), and the streaming parser alone at sizes the legacy path cannot reach
* in reasonable time.
*
* And the whole host cost of a streamed token, by component: the decoder, the server's text
* bookkeeping, the parser, the reader bridge, the chunk JSON, and the tool-call grammar the
* sampler drives (accept_token, and fill_mask once triggered) in prose, call structure, string
* values and typed values -- with every SSE event held to nlohmann's own serialisation of it.
* It also times a long reply streamed through the SSE layer, legacy ("old") against streaming
* ("new"), and the streaming parser alone at sizes the legacy path cannot reach; and the host cost
* of one streamed token by component (decoder, server text bookkeeping, parser, reader bridge,
* 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. */
#include "chatdiff.h"
#include "iface.h"
#include "sample/grammar.h"
#include "sample/vocab_view.h"
#include "server/adapters.h"
#include "server/json_partial.h"
#include "server/oai.h"
#include "text/chatfmt.h"
#include "text/token_view.h"
#include "text/tokenizer.h"
#include <nlohmann/json.hpp>
@@ -82,13 +80,17 @@ double since(clk::time_point t0) {
return std::chrono::duration<double>(clk::now() - t0).count();
}
std::vector<size_t> sizes(const char* s) {
/* "a,b,c" as byte counts, each a whole number >= 1; exits 2 naming `flag` on anything else. */
std::vector<size_t> sizes(const char* flag, const char* s) {
std::vector<size_t> v;
for (const char* p = s; *p;) {
v.push_back((size_t)std::strtoull(p, nullptr, 10));
const char* c = std::strchr(p, ',');
if (!c) break;
p = c + 1;
const std::string all = s;
size_t at = 0;
while (at <= all.size()) {
size_t c = all.find(',', at);
if (c == std::string::npos) c = all.size();
v.push_back((size_t)rad_flag_int("rad-chatparse", flag, all.substr(at, c - at).c_str(), 1,
INT64_MAX));
at = c + 1;
}
return v;
}
@@ -109,8 +111,8 @@ struct Tok {
return tok.init(vocab);
}
/* Tokenise as the model would have written the reply -- control tokens as themselves -- and
* decode it back one token at a time the way the server does. */
/* Tokenise as the model would have written the reply (control tokens as themselves) and
* decode it one token at a time as the server does. */
std::vector<std::string> pieces(const std::string& text,
const std::vector<std::string>& preserved) const {
std::vector<int32_t> ids;
@@ -170,11 +172,9 @@ void check_reply(const Bench& b, const Tok& t, const std::string& written, const
ty->bytes += text.size();
if (text != written) {
++ty->decoder_changed;
/* The decoder suppresses control tokens by design, and a reply may hold ones the format
* does not use. What must never go missing is a marker the format is MADE of -- that is
* the failure that turns a call into prose -- so a reply that lost one is shown. The turn
* terminators are control tokens the decoder never renders, and a marker overlapping one
* (`>` inside `<|im_end|>`) is not a marker the reply wrote. */
/* The decoder suppresses control tokens by design. A lost format marker, though, turns a
* call into prose, so such replies are shown. Turn terminators are never rendered, and a
* marker overlapping one (`>` inside `<|im_end|>`) does not count. */
std::vector<std::pair<size_t, size_t>> terms;
for (const std::string& t : b.model().terminators)
for (size_t at = written.find(t); at != std::string::npos; at = written.find(t, at + 1))
@@ -287,36 +287,6 @@ Timing time_old(const Bench& b, const std::vector<std::string>& pieces) {
/* ------------------------------------------------------------------ the per-token breakdown */
/* The sampler's view of the real vocabulary, built as core/engine_bringup.cpp builds it: pieces
* are what the decoder chain writes to the output stream, special tokens rendered. */
class RealView final : public VocabView {
public:
int init(std::shared_ptr<const Vocab> v) {
v_ = std::move(v);
RAD_TRY(tok_.init(v_));
pieces_.resize((size_t)v_->n_tokens());
for (int32_t i = 0; i < v_->n_tokens(); ++i)
pieces_[(size_t)i] = tok_.piece(i, /*render_special=*/true);
return RAD_OK;
}
int32_t n_tokens() const override { return v_ ? v_->n_tokens() : 0; }
const std::string& token_piece(int32_t id) const override {
static const std::string kEmpty;
return (id >= 0 && (size_t)id < pieces_.size()) ? pieces_[(size_t)id] : kEmpty;
}
bool is_eog(int32_t id) const override { return v_ && v_->is_eog(id); }
int tokenize(const std::string& s, std::vector<int32_t>* out) const override {
return out ? tok_.encode(s, *out, false, false) : RAD_E_INVAL;
}
int tokenize_special(const std::string& s, std::vector<int32_t>* out) const override {
return out ? tok_.encode(s, *out, false, true) : RAD_E_INVAL;
}
private:
std::shared_ptr<const Vocab> v_;
Tokenizer tok_;
std::vector<std::string> pieces_;
};
double median(std::vector<double> v) {
std::sort(v.begin(), v.end());
@@ -333,9 +303,8 @@ std::string per(const std::vector<double>& secs, size_t units) {
return b;
}
/* Every SSE event in `out` must be exactly what nlohmann writes for the value it carries: the
* payload parsed and dumped again gives the same bytes. A chunk writer that is not a DOM is held
* to the DOM's output this way. Returns the events that are not. */
/* Every SSE event in `out` must round-trip byte for byte through nlohmann parse and dump, which
* holds the non-DOM chunk writer to the DOM's output. Returns the events that do not. */
size_t sse_not_canonical(const std::string& out, size_t* events) {
size_t bad = 0;
for (size_t at = 0; at < out.size();) {
@@ -352,13 +321,11 @@ size_t sse_not_canonical(const std::string& out, size_t* events) {
return bad;
}
/* THE HOST COST OF ONE STREAMED TOKEN, by component, on the real tokenizer: the decoder, the
* server's text bookkeeping, the reply reader, the chunk JSON, and the tool-call grammar the
* sampler runs (accept_token, and fill_mask once it has triggered). Each component runs over the
* whole reply on its own, `reps` times; the medians are reported, with the spread. Returns the
* contract violations it saw: chunks that are not canonical JSON, or a grammar that refused the
* reply. */
int breakdown(const Bench& b, const Tok& tk, const RealView& view, int reps) {
/* Host cost of one streamed token by component, on the real tokenizer: decoder, server text
* bookkeeping, reply reader, chunk JSON, and the tool-call grammar (accept_token, and fill_mask once
* triggered). Each runs over the whole reply `reps` times; medians and spread are reported. Returns
* the contract violations: non-canonical chunk JSON, or a grammar that refused the reply. */
int breakdown(const Bench& b, const Tok& tk, const TokenView& view, int reps) {
const Model& m = b.model();
/* A long write with string values, and calls with integer and boolean values. */
std::string text = long_reply(m, 262144);
@@ -407,8 +374,8 @@ int breakdown(const Bench& b, const Tok& tk, const RealView& view, int reps) {
}
t_detok.push_back(since(c0));
/* The server's side of a token: the choice's text grows, and the stable prefix -- a
* UTF-8 boundary, no half escape -- is what goes to the stream. */
/* Server side of a token: the choice text grows, and its stable prefix (UTF-8 boundary,
* no half escape) is streamed. */
c0 = clk::now();
{
std::string acc;
@@ -478,8 +445,8 @@ int breakdown(const Bench& b, const Tok& tk, const RealView& view, int reps) {
std::printf(" %zu SSE events, %zu not canonical\n", events, bad);
int violations = (int)bad;
/* The grammar, as the server builds it for this request and the sampler drives it, one token
* at a time: a mask for every position once the grammar constrains, then the token. */
/* The grammar as the server builds it and the sampler drives it: once it constrains, a mask
* per position, then the token. */
ChatGrammarRequest gq;
gq.tools = &agent_tools();
gq.generation_prompt = b.prompt().generation_prompt;
@@ -572,13 +539,13 @@ int main(int argc, char** argv) {
if (eq == std::string::npos) { std::fprintf(stderr, "--model name=dir\n"); return 2; }
want.push_back({ v.substr(0, eq), v.substr(eq + 1) });
} else if (a == "--fuzz" && i + 1 < argc) {
fuzz = std::atoi(argv[++i]);
fuzz = (int)rad_flag_int("rad-chatparse", "--fuzz", argv[++i], 0, INT32_MAX);
} else if (a == "--long" && i + 1 < argc) {
old_sizes = sizes(argv[++i]);
old_sizes = sizes("--long", argv[++i]);
} else if (a == "--reps" && i + 1 < argc) {
reps = std::max(1, std::atoi(argv[++i]));
reps = (int)rad_flag_int("rad-chatparse", "--reps", argv[++i], 1, INT32_MAX);
} else if (a == "--new-long" && i + 1 < argc) {
new_sizes = sizes(argv[++i]);
new_sizes = sizes("--new-long", argv[++i]);
} else if (a[0] != '-') {
const std::pair<const char*, std::vector<const char*>> layout[] = {
{ "qwen3.8", { "Qwen3.8-Flash-Next", "Qwen3.8-27B-FP8" } },
@@ -689,7 +656,7 @@ int main(int argc, char** argv) {
nw.parser / text.size() * 1e9, nw.parser / p.size() * 1e6);
}
RealView view;
TokenView view;
if (view.init(tk.vocab) < 0) return 1;
violations += breakdown(b, tk, view, reps);
}
+173 -352
View File
@@ -1,26 +1,24 @@
/* rad-convert -- safetensors or GGUF in, .rad out.
*
* A .rad holds each logical weight as the canonical planes of its ENCODING (spec §4.1, §4.2):
* which kernel library rearranges them at load, and how, is not this tool's concern, and nothing
* here knows any kernel's layout. What it does is quantise. A RECIPE maps logical weight names to
* quantiser plugins and their options (spec §4.4); the first rule that matches a weight decides
* it, and a weight no rule matches keeps the checkpoint's own encoding -- which has to be one the
* engine serves as it is (bf16, f16, f32, block-scaled FP8), or the recipe is incomplete and the
* weight is named.
* A .rad holds each logical weight as the canonical planes of its encoding (spec §4.1, §4.2);
* kernel layouts are applied at load, not here. A recipe maps logical weight names to quantiser
* plugins and options (spec §4.4); the first matching rule decides. An unmatched weight keeps the
* checkpoint's encoding, which must be one the engine serves directly (bf16, f16, f32,
* block-scaled FP8), or the weight is reported.
*
* IT STILL RUNS DECLARE, for two reasons. The architecture plugin's name map is the only thing
* that knows which checkpoint tensors make a declared weight -- fusions, alternatives, expert
* slices. And declare is where every resolved kernel's layout hook is asked about the encoding
* the recipe plans (rad_weight_encoding answers with it): a recipe nothing can serve is refused
* before a byte is written, by the same check the engine makes at load.
* Declare still runs: the architecture plugin's name map says which checkpoint tensors make each
* weight (fusions, alternatives, expert slices), and each resolved kernel's layout hook is asked
* about the planned encoding (via rad_weight_encoding), so an unservable recipe is refused before
* anything is written, by the same check the engine makes at load.
*
* Every weight it quantises is measured against its source through the core's decoder, and the
* worst are reported: a format change that cannot be ranked is one nobody can argue about.
* Every quantised weight is measured against its source through the core's decoder, and the worst
* are reported.
*/
#include "iface.h"
#include "format/checkpoint.h"
#include "format/encoding.h"
#include "format/imatrix.h"
#include "format/quantise.h"
#include "format/recipe.h"
#include "plugin/registry.h"
#include "text/tokenizer.h"
@@ -51,8 +49,7 @@ namespace {
bool file_exists(const std::string& p) { std::ifstream f(p); return (bool)f; }
/* `blk.12.attn_q.weight` -> 12; -1 for a model-level name. The convention is GGUF's, and an
* imatrix's names follow it. */
/* `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;
size_t i = 4, v = 0;
@@ -61,77 +58,11 @@ int32_t layer_from_name(const std::string& n) {
return (int32_t)v;
}
/* ================================================================== the recipe, typed */
/* A rule with its quantiser found and its options typed by that quantiser's own table, once: a
* misspelt key is refused before declare, not discovered at the forty-thousandth weight. The
* RadParam strings point into `keys` and `vals`, which never change after build(). */
struct Compiled {
const RecipeRule* rule = nullptr;
const RadQuantizerInfo* q = nullptr;
std::vector<std::string> keys, vals;
std::vector<RadParam> params;
int build(const RecipeRule& r, Registry& reg, std::string* why) {
rule = &r;
const Registry::QuantRow* row = reg.quantizer(r.quantizer);
if (!row || !row->info) {
std::string have;
for (const auto& qr : reg.quantizers())
if (qr.info) have += std::string(have.empty() ? "" : ", ") + qr.info->name;
*why = r.origin + ": no quantiser '" + r.quantizer + "' is loaded (" +
(have.empty() ? std::string("none are -- is $RADIANCE_HOME/quantizers there?")
: "loaded: " + have) + ")";
return RAD_E_NOTFOUND;
}
q = row->info;
keys.reserve(r.options.size());
vals.reserve(r.options.size());
for (const auto& [k, v] : r.options) {
const RadQuantOption* opt = nullptr;
for (int i = 0; i < q->n_options; ++i)
if (k == q->options[i].key) opt = &q->options[i];
if (!opt) {
std::string takes;
for (int i = 0; i < q->n_options; ++i)
takes += std::string(i ? ", " : "") + q->options[i].key;
*why = r.origin + ": " + q->name + " takes no option '" + k + "' (it takes " +
takes + ")";
return RAD_E_INVAL;
}
char* end = nullptr;
if (opt->type == RAD_P_INT) {
const long long x = std::strtoll(v.c_str(), &end, 0);
if (!end || *end) { *why = r.origin + ": " + k + "=" + v + " is not an integer";
return RAD_E_INVAL; }
keys.push_back(k);
vals.push_back(v);
params.push_back(RAD_INT(nullptr, x));
} else if (opt->type == RAD_P_F64) {
const double x = std::strtod(v.c_str(), &end);
if (!end || *end) { *why = r.origin + ": " + k + "=" + v + " is not a number";
return RAD_E_INVAL; }
keys.push_back(k);
vals.push_back(v);
params.push_back(RAD_F64(nullptr, x));
} else {
keys.push_back(k);
vals.push_back(v);
params.push_back(RAD_STR(nullptr, nullptr));
}
}
for (size_t i = 0; i < params.size(); ++i) {
params[i].key = keys[i].c_str();
if (params[i].kind == RAD_P_STR) params[i].sval = vals[i].c_str();
}
return RAD_OK;
}
};
/* ================================================================== the plan */
/* One logical weight this run writes: where it comes from, what decides it, what it becomes. */
struct Logical {
CkptWeight src;
const Compiled* rule = nullptr;
const CompiledRule* rule = nullptr;
RadEncoding enc{};
int status = RAD_OK;
std::string why;
@@ -156,8 +87,8 @@ RadQuantWeight quant_weight(const Logical& L, const float* importance) {
return qw;
}
/* Movement-unit order: model-level weights first, then each layer's own, then its experts in id
* order with their slots adjacent -- which is what makes base + id * stride true. */
/* Movement-unit order: model-level weights, then each layer's own, then its experts in id order
* with their slots adjacent, so experts are addressable as base + id * stride. */
bool plan_less(const Logical* a, const Logical* b) {
auto key = [](const Logical* p) {
return std::make_tuple(p->layer < 0 ? -1 : p->layer, p->expert, p->slot, p->src.name);
@@ -165,34 +96,6 @@ bool plan_less(const Logical* a, const Logical* b) {
return key(a) < key(b);
}
/* THE IMATRIX'S COLUMN IMPORTANCES FOR A WEIGHT, when it has them: its sum of squared inputs a
* column, per call. The imatrix names a tensor the GGUF way without its suffix, and keeps a MoE
* layer's experts as one entry -- so `blk.5.ffn_down_exps.9.weight` is expert 9 of
* `blk.5.ffn_down_exps`. Empty when nothing matches or the widths disagree. */
std::vector<float> importance_of(const ImatrixFile& im, const std::string& name, int64_t cols) {
std::vector<float> out;
std::string base = name;
if (base.size() > 7 && base.compare(base.size() - 7, 7, ".weight") == 0)
base.resize(base.size() - 7);
int64_t ex = 0;
const ImatrixEntry* e = im.find(base);
if (!e) {
const size_t dot = base.find_last_of('.');
if (dot == std::string::npos) return out;
char* end = nullptr;
ex = std::strtoll(base.c_str() + dot + 1, &end, 10);
if (!end || *end || dot + 1 == base.size()) return out;
e = im.find(base.substr(0, dot));
if (!e || ex >= e->n_expert) return out;
}
if (!e->sum2 || e->cols != cols) return out;
double calls = e->counts ? (double)e->counts[ex] : (double)e->ncall;
if (calls <= 0) calls = 1;
out.resize((size_t)cols);
for (int64_t j = 0; j < cols; ++j) out[(size_t)j] = (float)(e->sum2[ex * cols + j] / calls);
return out;
}
void usage() {
std::printf(
"rad-convert -- safetensors or GGUF in, .rad out\n"
@@ -231,7 +134,8 @@ void usage() {
" first of bf16, fp8 at which every op resolves -- the container\n"
" is the same at either, so this only picks the kernels it checks\n"
" --max-spec N the max_spec declare is run at (default 4, or the block a\n"
" drafter states); 0 leaves a draft head out\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"
" it holds with the same encoding, quantiser, options and shape is\n"
" copied from it instead of quantised again\n"
@@ -250,6 +154,25 @@ void usage() {
" -h, --help\n");
}
/* Runs fn(a, m, &why) over rows [a, a + m) covering [0, n): in about 256 pieces across threads, or
* as one call when !parallel. Returns RAD_E_FORMAT with the first failure's message in *why. */
template <class F>
int for_row_pieces(int64_t n, bool parallel, std::string* why, F fn) {
const int64_t piece = parallel ? std::max<int64_t>(1, (n + 255) / 256) : n;
const int64_t np = (n + piece - 1) / piece;
int rc = RAD_OK;
#pragma omp parallel for schedule(dynamic, 1) if (parallel)
for (int64_t p = 0; p < np; ++p) {
const int64_t a = p * piece, m = std::min(piece, n - a);
std::string w1;
if (fn(a, m, &w1) != RAD_OK) {
#pragma omp critical(rad_convert_err)
if (rc == RAD_OK) { rc = RAD_E_FORMAT; *why = w1; }
}
}
return rc;
}
} /* namespace */
int main(int argc, char** argv) {
@@ -260,6 +183,7 @@ int main(int argc, char** argv) {
int64_t max_ctx = 0; /* 0: the checkpoint's training context */
static const int kMaxSpecDefault = 4;
int max_spec = kMaxSpecDefault;
bool max_spec_given = false;
int report_n = 20;
bool verbose = false, plan_only = false, list_quant = false;
std::string reuse_path, changed_path;
@@ -274,6 +198,9 @@ int main(int argc, char** argv) {
std::exit(2); }
return argv[++i];
};
auto num = [&](const char* what, int64_t lo, int64_t hi) {
return rad_flag_int("rad-convert", what, next(what), lo, hi);
};
if (a == "-h" || a == "--help") { usage(); return 0; }
else if (a == "-o" || a == "--out") out = next("--out");
else if (a == "--recipe") recipe_files.push_back(next("--recipe"));
@@ -293,12 +220,13 @@ int main(int argc, char** argv) {
}
set_kv.emplace_back(kv.substr(0, eq), kv.substr(eq + 1));
}
else if (a == "--max-tok") max_tok = std::atoll(next("--max-tok"));
else if (a == "--max-ctx") max_ctx = std::atoll(next("--max-ctx"));
else if (a == "--max-spec") max_spec = std::atoi(next("--max-spec"));
else if (a == "--max-tok") max_tok = num("--max-tok", 1, INT64_MAX);
else if (a == "--max-ctx") max_ctx = num("--max-ctx", 0, INT64_MAX);
else if (a == "--max-spec") { max_spec = (int)num("--max-spec", 0, INT32_MAX);
max_spec_given = true; }
else if (a == "--draft-model") draft_dir = next("--draft-model");
else if (a == "--plan-only") plan_only = true;
else if (a == "--report") report_n = std::atoi(next("--report"));
else if (a == "--report") report_n = (int)num("--report", 0, INT32_MAX);
else if (a == "--reuse") reuse_path = next("--reuse");
else if (a == "--changed") changed_path = next("--changed");
else if (a == "--in-place") in_place = true;
@@ -358,8 +286,8 @@ int main(int argc, char** argv) {
if (out.empty()) out = reuse_path;
}
if (in.empty() || out.empty()) { usage(); return 2; }
/* THE OUTPUT IS OPENED WITH O_TRUNC. Pointed at the --reuse container it would empty the file
* every weight is about to be copied from; --in-place is the way to write into that file. */
/* The output is opened with O_TRUNC, so it must not be the --reuse container unless
* --in-place is given. */
if (!reuse_path.empty()) {
struct stat so{}, sr{};
const bool same = ::stat(out.c_str(), &so) == 0 && ::stat(reuse_path.c_str(), &sr) == 0 &&
@@ -392,22 +320,22 @@ int main(int argc, char** argv) {
Checkpoint ck;
if (ck.open(in) < 0) return 1;
MetaOwn& meta = ck.meta();
/* The drafter merges BEFORE declare: the architecture plugin decides whether to declare a
* draft block by looking for `draft.architectures` in the table. */
/* Merge the drafter before declare: the architecture plugin declares a draft block only if
* `draft.architectures` is present. */
if (!draft_dir.empty()) {
if (ck.add_draft(draft_dir, "draft.") < 0) return 1;
RAD_INFO("drafter %s (%s)", draft_dir.c_str(),
rad_meta_gets(&meta.m, "draft.architectures", "?"));
}
if (!arch_override.empty()) meta.arch = arch_override;
/* --set, added after the checkpoint's own config and the drafter's, so an operator's key is
* the last word. Declare reads RadModelMeta and so does the engine's, from the container's
* header, so a choice that changes the graph is stated once and held at both. */
/* --set is applied last, so it overrides the checkpoint's and drafter's config. Declare here
* 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);
/* ...AND THE DESCRIPTOR FOLLOWS. The plugin pair is derived from quantization_config, so a
* --set of it re-derives the pair rather than leaving the container stating one format and
* selecting the plugin of another: a bf16 checkpoint whose recipe writes Qwen's block fp8 is
* converted for qwen35_fp8 by stating what that release states. */
/* 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
* states. */
for (const auto& kv : set_kv)
if (kv.first.rfind("quantization_config.", 0) == 0) {
meta.quant = quant_descriptor(meta);
@@ -415,13 +343,12 @@ int main(int argc, char** argv) {
break;
}
/* THE CONTAINER --reuse NAMES, read with pread and never paged through its mapping. */
/* 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;
/* THE TENSORS --changed NAMES: a checkpoint that differs from the --reuse container's own in
* these and nowhere else -- a weight edit, a fine-tune of some matrices. --reuse matches a
* weight on how it was converted and not on its source bytes, so without this list it would
* copy the old weight for every one of them. */
/* --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. */
std::unordered_set<std::string> changed, changed_read;
if (!changed_path.empty()) {
std::ifstream cf(changed_path);
@@ -438,9 +365,8 @@ int main(int argc, char** argv) {
return 1;
}
}
/* EXTENDED, NOT RE-DECIDED. The container's radiance.* keys are the convert-time choices its
* weights were made under, and a run that keeps those weights declares under the same ones.
* `radiance.encoder` is not a choice; this run derives it. */
/* --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;
if (in_place) {
for (int64_t i = 0; i < reuse.meta_count(); ++i) {
@@ -455,8 +381,7 @@ int main(int argc, char** argv) {
++inherited;
}
}
/* Published once more, unconditionally: every merge above may have moved the strings the
* previous finish() pointed at. */
/* Always re-publish: the merges above may have moved the strings finish() pointed at. */
meta.finish();
if (inherited)
RAD_INFO("--in-place: %d radiance.* key(s) carried over from %s", inherited,
@@ -483,15 +408,15 @@ int main(int argc, char** argv) {
"recipe is checked against");
return 1;
}
/* AN IMPORTED QUANTISATION IS RECORDED AS THE DESCRIPTOR OF THE PLUGIN THAT SERVES IT: every
* weight states its own encoding in the container, and the engine selects by exact match. */
/* 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) {
meta.quant = plugins.arch_quant;
meta.finish();
}
Registry& reg = rad_tools_registry();
std::deque<Compiled> compiled;
std::map<const RecipeRule*, const Compiled*> by_rule;
std::deque<CompiledRule> compiled;
std::map<const RecipeRule*, const CompiledRule*> by_rule;
for (const RecipeRule& r : recipe.rules()) {
compiled.emplace_back();
std::string why;
@@ -508,40 +433,31 @@ int main(int argc, char** argv) {
ctx.rank = 0;
ctx.world_size = 1;
ctx.max_tok = max_tok;
/* THE CONTEXT BOUND IS A DECLARE INPUT: an architecture whose graph changes shape with it --
* Qwen3.8-Flash-Next's QSA is exactly dense attention up to its indexer budget and a different
* attention above -- can refuse to declare at the checkpoint's own number. */
/* The context bound is a declare input: an architecture whose graph depends on it (e.g.
* Qwen3.8-Flash-Next's QSA, dense up to its indexer budget) may refuse some values. */
ctx.max_seqs = 256;
ctx.max_ctx = max_ctx > 0 ? max_ctx : meta.m.n_ctx_train;
ctx.scope = "";
/* NON-ZERO ON PURPOSE: a container carries every weight any deployment of the model could ask
* for, so a draft head is declared even though converting is not drafting. A drafter trained
* for one block says so (rad_arch_probe), as it does for `--num-speculative-tokens auto`. */
if (max_spec == kMaxSpecDefault) {
RadArchProbe probe{};
(void)rad_tools_probe(plugins, meta.m, &probe);
if (probe.draft_depth > 0 && probe.draft_depth_fixed) {
max_spec = probe.draft_depth;
RAD_INFO("declaring at max_spec %d, the only depth this drafter serves", max_spec);
}
RadArchProbe probe{};
(void)rad_tools_probe(plugins, meta.m, &probe);
/* Non-zero on purpose: the container carries every weight any deployment may need, including
* the draft head. A drafter trained for one fixed depth reports it via rad_arch_probe, which
* replaces the default but not a depth the command line states. */
if (!max_spec_given && probe.draft_depth > 0 && probe.draft_depth_fixed) {
max_spec = probe.draft_depth;
RAD_INFO("declaring at max_spec %d, the only depth this drafter serves", max_spec);
}
ctx.max_spec = max_spec;
/* AND THE ENCODER, for the draft head's reason. */
/* Likewise declare the encoders, the vision tower at the engine's default patch bound. */
if (rad_meta_geti(&meta.m, "vision_config.patch_size", 0) > 0) {
ctx.max_enc_patches = 16384;
RadArchProbe probe{};
(void)rad_tools_probe(plugins, meta.m, &probe);
if (probe.enc_merge > 1) ctx.max_enc_patches -= ctx.max_enc_patches % probe.enc_merge;
}
{
RadArchProbe probe{};
(void)rad_tools_probe(plugins, meta.m, &probe);
ctx.max_audio_frames = probe.audio_frames > 0 ? probe.audio_frames : 0;
}
ctx.max_audio_frames = probe.audio_frames > 0 ? probe.audio_frames : 0;
/* THE ENCODING EVERY WEIGHT WILL HAVE, answered to declare as rad_weight_encoding: the
* recipe's when a rule matches, the checkpoint's own when it is trivial. Remembered once
* answered; a name the name map does not know yet is not, since declare may map it later. */
/* Each weight's planned encoding, answered to declare via rad_weight_encoding: the recipe's
* when a rule matches, else the checkpoint's own when trivial. Answers are memoised, except
* not-found names, which declare may map later. */
std::map<std::string, Logical> logical;
auto plan_weight = [&](const std::string& name, const Program& prog, bool optional,
Logical** out) -> int {
@@ -562,7 +478,7 @@ int main(int argc, char** argv) {
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 -- a norm under a pattern meant for matrices -- and kept as it is */
/* declined (e.g. a norm under a matrix pattern): keep as is */
L.rule = nullptr;
L.enc = L.src.enc;
} else if (st != RAD_OK) {
@@ -602,8 +518,8 @@ int main(int argc, char** argv) {
return n;
};
/* AN OP THAT RESOLVED IN NO DOMAIN has no kernel to read its weights, so nothing has checked
* the encoding planned for them. Device holes alone are placement options, not refusals. */
/* Ops resolved in no domain: nothing has checked their weights' planned encoding. Device-only
* holes are placement options, not refusals. */
auto dead_ops = [](const Program& p) {
size_t n = 0;
for (size_t i = 1; i < p.ops.size(); ++i) {
@@ -614,11 +530,9 @@ int main(int argc, char** argv) {
}
return n;
};
/* THE CACHE WIDTH IS A SERVE CHOICE the container does not record: the weights and their
* encodings are the same at either, and only the kernels that check them differ -- an
* attention that writes an fp8 cache may have no bf16 form. Unnamed, the first width at which
* every op resolves is the one checked against; if none does, the one with the fewest holes
* is reported. */
/* The KV cache width is a serve-time choice the container does not record; only the kernels
* differ (an fp8-cache attention may have no bf16 form). Without --kv-cache-dtype, check
* against the first width at which every op resolves, else report the one with fewest holes. */
const std::vector<int> widths = kv_dtype != RAD_DT_INVALID
? std::vector<int>{ kv_dtype }
: std::vector<int>{ RAD_BF16, RAD_F8E4M3 };
@@ -681,7 +595,7 @@ int main(int argc, char** argv) {
L->slot, g.layer, g.expert, g.slot);
++bad;
}
/* THE ENCODING DECLARE CHOSE KERNELS FOR IS THE ONE THAT WILL BE WRITTEN. */
/* The encoding declare chose kernels for must be the one written. */
if (!w.enc_known || !rad_enc_equal(&w.enc, &L->enc)) {
RAD_ERR("'%s' was declared over an encoding of '%s' other than the one planned for "
"it", w.name.c_str(), w.source.c_str());
@@ -735,16 +649,14 @@ int main(int argc, char** argv) {
RAD_TRY(in_place ? w.begin_append(out.c_str(), reuse) : w.begin(out.c_str()));
w.set_arch(meta.arch);
/* An extended container keeps its name: the checkpoint this run reads its new weights from
* need not be the one it was made from. */
/* An extended container keeps its name; this run's checkpoint need not be its original. */
w.set_model_name(in_place ? std::string(reuse.str(reuse.header().model_name))
: (meta.name.empty() ? meta.arch : meta.name));
w.set_quant(meta.quant);
w.set_recipe(in_place && recipe.empty() ? std::string(reuse.str(reuse.header().recipe))
: recipe.text());
/* The checkpoint as its last two path components -- for a Hugging Face download, the
* repository id. The rest of the path is where one machine keeps its models, and a container
* is meant to leave that machine. */
/* Record the checkpoint as its last two path components (a Hugging Face repository id), not
* a machine-local path. */
std::string ck_id = ck.path();
while (ck_id.size() > 1 && ck_id.back() == '/') ck_id.pop_back();
if (const size_t a = ck_id.find_last_of('/'); a != std::string::npos && a > 0)
@@ -769,8 +681,8 @@ int main(int argc, char** argv) {
w.meta_f("rms_eps", meta.m.rms_eps);
w.meta_f("rope_theta", meta.m.rope_theta);
for (int i = 0; i < meta.m.n_kv; ++i) w.meta_s(meta.m.kv_key[i], meta.m.kv_val[i]);
/* THE CONTAINER CARRIES AN ENCODER'S WEIGHTS: what `--mm-max-patches auto` keys on. */
/* The encoders the container carries, by name: a vision tower, an audio encoder, or both. */
/* The encoders the container carries, by name (vision, audio or both); `--mm-max-patches auto`
* keys on this. */
{
std::string enc;
if (prog.encoder.modalities != 0) enc = prog.encoder_name;
@@ -781,23 +693,18 @@ int main(int argc, char** argv) {
/* ---------------------------------------------------------------- the weights
*
* EVERY WEIGHT IS ADDED FIRST, IN PLAN ORDER, AND WRITTEN AFTER IN ANY ORDER. Adding one is
* what places it -- its planes' offsets in the blob follow from the ones before it -- and that
* is the only part of the writer with an order; a plane write is a pwrite at its own offset.
* So the writing is parallel: a Flash-Next checkpoint is 49152 expert slices of a few
* megabytes each, and one at a time -- decode, a quantiser's OpenMP region too short to
* amortise its own fork, the error -- it keeps about four of thirty-two cores busy for an
* hour.
* All weights are added first in plan order, which fixes their plane offsets; plane writes are
* then pwrites at their own offsets in any order, so writing is parallel (a Flash-Next
* checkpoint is 49152 expert slices of a few MB each).
*
* A SMALL WEIGHT IS ONE THREAD'S. The pool takes them in plan order, which is roughly file
* order, and nested parallelism is off, so a quantiser's own OpenMP region runs on the thread
* that called it. A LARGE ONE IS EVERY THREAD'S: those run after, one at a time, with the
* decode, the quantiser and the error each parallel over rows -- a 51 GB n-gram table, an
* lm_head, the attention linears. */
* 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. */
#ifdef _OPENMP
omp_set_max_active_levels(1);
#endif
constexpr int64_t kChunk = (int64_t)64 << 20;
constexpr int64_t kChunk = kQuantBandBytes; /* copies and joins move this much at once */
constexpr int64_t kSmall = (int64_t)32 << 20; /* f32 bytes one thread quantises alone */
struct Job {
@@ -826,9 +733,9 @@ int main(int argc, char** argv) {
for (int k = 0; k < L.enc.n_planes; ++k)
plane_total += rad_enc_plane_bytes(&L.enc.plane[k], L.src.rows, L.src.cols);
/* --- REUSED: the same encoding, quantiser, options and shape in the --reuse container
* are the same planes, given the same checkpoint -- which --reuse leaves to the operator,
* since nothing in either container records a Hessian's contents. */
/* --- Reused: the same encoding, quantiser, options and shape in the --reuse container give
* the same planes, assuming the same checkpoint (the operator's responsibility; neither
* container records e.g. a Hessian's contents). */
const RadFileEntry* re = reuse.is_open() ? reuse.find(ww.name) : nullptr;
const bool reads_changed =
!changed.empty() && ckpt_reads_any(L.src, changed, &changed_read);
@@ -865,8 +772,7 @@ int main(int argc, char** argv) {
if (idx < 0) { w.abort(); return 1; }
jobs.push_back(Job{ Lp, idx, re, plane_total });
}
/* A NAME NO WEIGHT READS changes nothing, so it is a typo or a tensor this program does not
* convert -- and either way the operator believes a weight is being converted that is not. */
/* A --changed name no weight reads is a typo or an unconverted tensor; refuse it. */
if (!changed.empty()) {
std::vector<std::string> unread;
for (const std::string& n : changed)
@@ -883,8 +789,8 @@ int main(int argc, char** argv) {
}
/* ---------------------------------------------------------------- vocab */
/* core/text interprets the declared chain and serialises it; the writer places it and owns the
* one string blob its token text goes into. */
/* core/text interprets and serialises the declared chain; the writer places it and owns the
* string blob holding token text. */
struct WriterSink : StringSink {
RadWriter* w;
rad_stroff intern(std::string_view s) override { return w->intern_string(s); }
@@ -895,9 +801,9 @@ int main(int argc, char** argv) {
if (!tokjson.empty()) {
if (parse_tokenizer_json(tokjson.c_str(), vb) < 0) { w.abort(); return 1; }
} else if (ck.is_gguf()) {
/* GGUF has no declared chain, only the pre-tokeniser NAME llama.cpp derived by hashing the
* original tokenizer.json. core/text reconstructs from that name where it can and REFUSES
* where it cannot -- point --tokenizer at the real file when this fails. */
/* GGUF has no declared chain, only the pre-tokeniser name llama.cpp derived by hashing the
* original tokenizer.json. core/text reconstructs from the name where it can and refuses
* otherwise (then pass --tokenizer). */
if (vocab_from_gguf(ck.gguf(), vb) < 0) {
RAD_ERR("pass --tokenizer <tokenizer.json> to bake the declared chain instead of the "
"one a pre-tokeniser name implies.");
@@ -914,8 +820,7 @@ int main(int argc, char** argv) {
w.abort();
return 1;
}
/* Serialised at section offset 0: the writer does not know where the section lands until it
* has sized the string blob this call is still growing, so finish() rebases. */
/* 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; }
if (w.set_vocab_section(vocab_blob.data(), (int64_t)vocab_blob.size()) < 0) {
@@ -925,8 +830,7 @@ int main(int argc, char** argv) {
/* ---------------------------------------------------------------- expert profile */
if (im.entries().size()) {
/* Shares are per layer, so the planner compares experts within a layer rather than
* across layers with different token counts. */
/* Shares are normalised per layer, so experts are compared within a layer. */
std::map<int, std::vector<std::pair<int, double>>> per_layer;
for (const auto& e : im.entries()) {
if (e.n_expert <= 1 || !e.counts) continue;
@@ -954,10 +858,9 @@ int main(int argc, char** argv) {
w.add_profile(pr.layer, pr.expert, pr.share);
}
/* EVERY TABLE IS COMPLETE NOW -- the weights placed, the vocab and the profile in -- so the
* blob can be written where it will stay rather than spilled and copied in at the end, which
* on a 113 GiB container is minutes of the disk doing nothing but move it (RadWriter::seal).
* An extended container already writes in place. */
/* All tables are complete, so seal: the blob is then written in its final place rather than
* spilled and copied at the end (RadWriter::seal). An extended container already writes in
* place. */
if (!in_place && w.seal() < 0) { w.abort(); return 1; }
std::atomic<int64_t> written{0}, reused{reused_inplace}, n_reused{n_inplace};
@@ -965,19 +868,9 @@ int main(int argc, char** argv) {
/* Read `n` rows from `r0` of a checkpoint weight as f32, the rows split across threads. */
auto rows_f32 = [](const CkptWeight& src, int64_t r0, int64_t n, float* out,
std::string* why) -> int {
const int64_t piece = std::max<int64_t>(1, (n + 255) / 256);
const int64_t np = (n + piece - 1) / piece;
int rc = RAD_OK;
#pragma omp parallel for schedule(dynamic, 1)
for (int64_t p = 0; p < np; ++p) {
const int64_t a = p * piece, m = std::min(piece, n - a);
std::string w1;
if (ckpt_rows_f32(src, r0 + a, m, out + a * src.cols, &w1) != RAD_OK) {
#pragma omp critical(rad_convert_err)
if (rc == RAD_OK) { rc = RAD_E_FORMAT; *why = w1; }
}
}
return rc;
return for_row_pieces(n, true, why, [&](int64_t a, int64_t m, std::string* w1) {
return ckpt_rows_f32(src, r0 + a, m, out + a * src.cols, w1);
});
};
/* One weight, start to finish. Its own buffers, so any thread may run it. */
@@ -1008,9 +901,9 @@ int main(int argc, char** argv) {
return RAD_OK;
}
/* --- KEPT AS THE CHECKPOINT HOLDS IT: each plane's bytes from the mapped source, joined
* where the name map joins pieces. A join along rows is the pieces one after another, so
* each goes straight from the mapping; any other join is assembled a chunk at a time. */
/* --- Kept as the checkpoint holds it, joining pieces where the name map does. A row join
* is the pieces in sequence, written straight from the mapping; other joins are assembled
* a chunk at a time. */
if (!L.rule) {
for (int k = 0; k < L.enc.n_planes; ++k) {
const std::vector<const SrcTensor*>& src = k == 0 ? L.src.pieces : L.src.scales;
@@ -1055,139 +948,67 @@ int main(int argc, char** argv) {
return RAD_OK;
}
/* --- QUANTISED, a block of rows at a time. The quantiser says how many rows one call
* may take (0: all of them); the converter takes a multiple of that near 64 MiB of f32,
* so a 51 GB table streams and a GPTQ weight is handed whole. A plane banded by rows is
* written as each block lands; a plane that covers every row -- a codebook, a per-tensor
* scale -- is held until the last call has written it. */
const Compiled& c = *L.rule;
const std::vector<float> imp = imat_path.empty()
? std::vector<float>()
: importance_of(im, name, L.src.cols);
/* --- Quantised a band of rows at a time, by the loop core/format/quantise.h describes. */
const CompiledRule& c = *L.rule;
std::vector<float> imp;
if (!imat_path.empty()) (void)im.importance_for(name, L.src.cols, &imp);
const RadQuantWeight qw = quant_weight(L, imp.empty() ? nullptr : imp.data());
{
/* the group is known now and the encoding was chosen without it: it may not move */
RadEncoding again{};
if (c.q->encoding(c.params.data(), (int)c.params.size(), &qw, &again) != RAD_OK ||
!rad_enc_equal(&again, &L.enc)) {
RAD_ERR("'%s': %s answers with another encoding once it is told the weight's "
"movement group, and declare could not tell it that. An encoding may "
"depend on the weight's name and shape, not on where it is placed.",
name.c_str(), c.q->name);
return RAD_E_STATE;
}
}
const int64_t R = L.src.rows, C = L.src.cols;
int64_t rb = c.q->row_block ? c.q->row_block(c.params.data(), (int)c.params.size(), &qw)
: 0;
if (rb <= 0 || rb > R) rb = R;
int64_t blk = rb;
if (rb < R) {
const int64_t want = std::max<int64_t>(1, kChunk / std::max<int64_t>(C * 4, 1));
blk = std::max<int64_t>(rb, want - want % rb);
if (blk > R) blk = R;
}
const int np = L.enc.n_planes;
std::vector<int64_t> prow_bytes((size_t)np), pband((size_t)np);
std::vector<std::vector<uint8_t>> whole((size_t)np), band((size_t)np);
bool misaligned = false;
for (int k = 0; k < np; ++k) {
const RadEncPlane& p = L.enc.plane[k];
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&p, R, C, &pr, &pc);
prow_bytes[(size_t)k] = rad_enc_row_bytes(p.dtype, pc);
const bool banded = p.kind == RAD_PLANE_TILED && p.block[0] > 0;
pband[(size_t)k] = banded ? p.block[0] : 0;
if (banded && blk < R && blk % p.block[0]) misaligned = true;
if (!banded) whole[(size_t)k].assign((size_t)(pr * prow_bytes[(size_t)k]), 0);
}
if (misaligned) {
RAD_ERR("'%s': %s takes %lld rows a call, which splits a block of its own encoding's "
"scales", name.c_str(), c.q->name, (long long)rb);
return RAD_E_SHAPE;
}
/* Measured through the decoder every reader uses: the core's for plain and affine, the
* quantiser's own hook for a scheme of its own (core/format/encoding.h). A quantiser's
* decoder is not promised to be reentrant, so its rows are decoded in one call. */
const int64_t C = L.src.cols;
/* Error is measured through the decoder readers use: the core's for plain and affine, the
* quantiser's hook for its own scheme (core/format/encoding.h). Quantiser decoders need
* not be reentrant, so those rows are decoded in one call. */
bool core_decodes = true;
const bool own_scheme = !rad_enc_is(&L.enc, "plain") && !rad_enc_is(&L.enc, "affine");
std::vector<float> f, ref, dec;
std::vector<float> dec;
double num = 0, den = 0, num_i = 0, den_i = 0;
for (int64_t r0 = 0; r0 < R; r0 += blk) {
const int64_t n = std::min(blk, R - r0);
f.resize((size_t)(n * C));
QuantIo io;
io.read = [&](int64_t r0, int64_t n, float* out, std::string* why) {
return rows_f32(L.src, r0, n, out, why);
};
io.write = [&](int k, int64_t off, const void* data, int64_t bytes) {
return w.write_plane(idx, k, off, data, bytes);
};
/* The error over exactly these rows. */
io.band = [&](int64_t, int64_t n, const float* ref, const void* const* pd) {
if (!core_decodes) return;
EncodedView v;
std::string why;
if (rows_f32(L.src, r0, n, f.data(), &why) != RAD_OK) {
RAD_ERR("'%s': %s", name.c_str(), why.c_str());
return RAD_E_FORMAT;
enc_view(L.enc, n, C, pd, &v);
dec.resize((size_t)(n * C));
const int drc = for_row_pieces(n, !own_scheme, &why,
[&](int64_t a, int64_t m, std::string* w1) {
return enc_decode_rows(v, a, m, dec.data() + a * C, w1);
});
if (drc != RAD_OK) {
RAD_WARN("'%s': nothing decodes what %s wrote (%s); its error is not reported",
name.c_str(), c.q->name, why.c_str());
core_decodes = false;
return;
}
ref = f; /* a quantiser may rotate its input in place */
std::vector<void*> ptr((size_t)np);
for (int k = 0; k < np; ++k) {
if (!pband[(size_t)k]) { ptr[(size_t)k] = whole[(size_t)k].data(); continue; }
const int64_t rows_k = (n + pband[(size_t)k] - 1) / pband[(size_t)k];
band[(size_t)k].assign((size_t)(rows_k * prow_bytes[(size_t)k]), 0);
ptr[(size_t)k] = band[(size_t)k].data();
const float* pi = imp.empty() ? nullptr : imp.data();
const int64_t cnt = n * C;
#pragma omp parallel for reduction(+ : num, den, num_i, den_i) schedule(static)
for (int64_t i = 0; i < cnt; ++i) {
const double d = (double)ref[(size_t)i] - dec[(size_t)i];
const double x = ref[(size_t)i];
num += d * d;
den += x * x;
if (pi) {
const double wj = pi[i % C];
num_i += wj * d * d;
den_i += wj * x * x;
}
}
const int st = c.q->quantize(c.params.data(), (int)c.params.size(), &qw, f.data(),
r0, n, ptr.data());
};
{
std::string why;
const int st = quantise_weight(*c.q, c.params.data(), (int)c.params.size(), qw, L.enc,
kQuantBandBytes, io, &why);
if (st != RAD_OK) {
RAD_ERR("'%s': %s could not quantise rows [%lld, %lld): %s", name.c_str(),
c.q->name, (long long)r0, (long long)(r0 + n), rad_strerror(st));
RAD_ERR("'%s': %s", name.c_str(), why.c_str());
return st;
}
for (int k = 0; k < np; ++k) {
if (!pband[(size_t)k]) continue;
if (w.write_plane(idx, k, (r0 / pband[(size_t)k]) * prow_bytes[(size_t)k],
band[(size_t)k].data(), (int64_t)band[(size_t)k].size()) !=
RAD_OK)
return RAD_E_IO;
}
/* THE ERROR, through the core's decoder over exactly these rows. */
if (core_decodes) {
EncodedView v;
const void* const* pd = (const void* const*)ptr.data();
enc_view(L.enc, n, C, pd, &v);
dec.resize((size_t)(n * C));
const int64_t piece = own_scheme ? n : std::max<int64_t>(1, (n + 255) / 256);
const int64_t npc = (n + piece - 1) / piece;
int drc = RAD_OK;
#pragma omp parallel for schedule(dynamic, 1) if (!own_scheme)
for (int64_t p = 0; p < npc; ++p) {
const int64_t a = p * piece, m = std::min(piece, n - a);
std::string w1;
if (enc_decode_rows(v, a, m, dec.data() + a * C, &w1) != RAD_OK) {
#pragma omp critical(rad_convert_err)
if (drc == RAD_OK) { drc = RAD_E_FORMAT; why = w1; }
}
}
if (drc != RAD_OK) {
RAD_WARN("'%s': nothing decodes what %s wrote (%s); its error is not "
"reported", name.c_str(), c.q->name, why.c_str());
core_decodes = false;
} else {
const float* pi = imp.empty() ? nullptr : imp.data();
const int64_t cnt = n * C;
#pragma omp parallel for reduction(+ : num, den, num_i, den_i) schedule(static)
for (int64_t i = 0; i < cnt; ++i) {
const double d = (double)ref[(size_t)i] - dec[(size_t)i];
const double x = ref[(size_t)i];
num += d * d;
den += x * x;
if (pi) {
const double wj = pi[i % C];
num_i += wj * d * d;
den_i += wj * x * x;
}
}
}
}
}
for (int k = 0; k < np; ++k)
if (!pband[(size_t)k] &&
w.write_plane(idx, k, 0, whole[(size_t)k].data(),
(int64_t)whole[(size_t)k].size()) != RAD_OK)
return RAD_E_IO;
if (core_decodes && den > 0) L.err = std::sqrt(num / den);
if (core_decodes && den_i > 0) L.err_imp = std::sqrt(num_i / den_i);
written += j.bytes;
+57 -81
View File
@@ -6,44 +6,40 @@
* [--walks N] [--walk-steps N] [--passes N] [--seed N]
* [--oracle cold|all|off]
*
* WHY A TOOL AND NOT ONLY A TEST. The mask engine is a precomputed plan over a vocabulary, and
* how large a key's remainder is, how many keys a grammar needs and what a mask costs are all
* properties of the vocabulary's real piece-length and byte distributions. A synthetic vocabulary
* in ctest exercises the same code paths and is held to the same oracle, but it cannot say what a
* quarter-million-piece byte-level vocabulary costs. This runs the real thing.
* A tool as well as a test: mask cost, key remainder sizes and key counts depend on the real
* vocabulary's piece-length and byte distributions. ctest's synthetic vocabulary covers the same
* code against the same oracle but cannot measure a quarter-million-piece byte-level vocabulary.
*
* WHAT IT RUNS, for each grammar -- the chat template's tool-call grammar with parallel tool calls
* off and on, a set of JSON-schema grammars, and any client GBNF given on the command line:
* For each grammar (the chat template's tool-call grammar with parallel tool calls off and on, a
* set of JSON-schema grammars, and any client GBNF given) it runs:
*
* compile from nothing, on a program no earlier run warmed: wall time, what the plan holds,
* and what the process's resident set grew by;
* replay realistic outputs (four agent tool calls; a document per schema) tokenised and
* driven exactly as Sampler::build_step drives a constrained sequence at depth-3
* speculation -- push, accept the drafts, mask every position, roll back, accept --
* timing the host work of each step, first on the cold program and then warm;
* walks random walks that take admissible tokens from the mask, draft a speculative window
* of up to three tokens (mostly admissible, sometimes not), verify it as the engine
* does and accept the verified prefix;
* oracle every mask computed rather than served from the cache (or every mask, with
* --oracle all) compared bit for bit, and by status, with upstream's candidate walk.
* compile from a cold program: wall time, plan contents, and resident-set growth;
* replay realistic outputs (four agent tool calls; a document per schema) driven exactly as
* Sampler::build_step drives a constrained sequence at depth-3 speculation (push,
* accept the drafts, mask every position, roll back, accept), timing each step's
* host work cold and then warm;
* walks random walks that draft a window of up to three tokens (mostly admissible), verify
* it as the engine does and accept the verified prefix;
* oracle every computed mask (or every mask, with --oracle all) compared bit for bit and by
* status with upstream's candidate walk.
*
* THE TIMING AND THE ORACLE ARE TWO PASSES, each over a program compiled for it, taking the same
* walks. The oracle rescans the whole vocabulary per stack and churns through tens of megabytes
* doing it, and a mask timed right after one is timed with every cache line it needs evicted --
* which says something about the oracle and nothing about the engine.
* Timing and oracle are separate passes over separately compiled programs, taking the same walks:
* the oracle rescans the vocabulary per stack and would evict the caches a timed mask needs.
*
* It reports mask latency cold (computed) and warm (served from the program's cache) as
* p50/p99/max -- computed masks at a state carrying a split character separately, since they are
* served from the vocabulary's resume index -- the replay's per-step cost, compile time, memory
* and every mismatch, and exits 1 if there was one. With --oracle off it is a latency run only.
* Reports cold (computed) and warm (cached) mask latency as p50/p99/max, with computed masks at a
* state carrying a split character listed separately (they come from the vocabulary's resume
* index); plus per-step replay cost, compile time, memory and every mismatch. Exits 1 on any
* mismatch. With --oracle off it is a latency run only.
*/
#include "gbnf_oracle.h"
#include "iface.h"
#include "rad_internal.h"
#include "sample/gbnf.h"
#include "sample/grammar.h"
#include "sample/vocab_view.h"
#include "text/chat.h"
#include "text/token_view.h"
#include "text/tokenizer.h"
#include <nlohmann/json.hpp>
@@ -69,34 +65,6 @@ namespace {
/* ================================================================== the vocabulary */
/* The engine's view of a real vocabulary, built the way core/engine_bringup.cpp builds it: pieces
* are what the decoder chain writes to the output stream, special tokens rendered. */
class RealView final : public VocabView {
public:
int init(std::shared_ptr<const Vocab> v) {
v_ = std::move(v);
RAD_TRY(tok_.init(v_));
pieces_.resize((size_t)v_->n_tokens());
for (int32_t i = 0; i < v_->n_tokens(); ++i)
pieces_[(size_t)i] = tok_.piece(i, /*render_special=*/true);
return RAD_OK;
}
int32_t n_tokens() const override { return v_ ? v_->n_tokens() : 0; }
const std::string& token_piece(int32_t id) const override {
static const std::string kEmpty;
return (id >= 0 && (size_t)id < pieces_.size()) ? pieces_[(size_t)id] : kEmpty;
}
bool is_eog(int32_t id) const override { return v_ && v_->is_eog(id); }
int tokenize(const std::string& s, std::vector<int32_t>* out) const override {
return out ? tok_.encode(s, *out, false, false) : RAD_E_INVAL;
}
const Tokenizer& tok() const { return tok_; }
private:
std::shared_ptr<const Vocab> v_;
Tokenizer tok_;
std::vector<std::string> pieces_;
};
std::string slurp(const std::string& p, bool* ok) {
std::ifstream f(p, std::ios::binary);
@@ -147,15 +115,15 @@ struct Dist {
enum class OracleMode { Off, Cold, All };
struct Run {
const RealView* view = nullptr;
const TokenView* view = nullptr;
OracleMode oracle = OracleMode::Cold;
int64_t n_words = 0;
Dist cold, cold_split, warm;
int64_t compared = 0, mismatches = 0;
std::vector<int32_t> structural; /* pieces that carry structure, to steer the walks */
/* One mask, timed and classified by whether the program had to compute it -- or, on the
* oracle's pass, held to the oracle and not timed. */
/* One mask: timed and classified as computed or cached, or on the oracle pass, compared and
* not timed. */
int mask(const GbnfGrammar& g, uint32_t* m, const char* where, double* engine_ms = nullptr) {
const uint64_t w0 = g.masks_walked();
const bool split = g.partial().n_remain > 0;
@@ -272,8 +240,8 @@ std::string go_file() {
return s;
}
/* Four calls an agent makes, in the XML-parameter tool-call syntax. A template with another
* syntax does not admit them and is exercised by the walks alone. */
/* Four agent tool calls in the XML-parameter syntax. Templates with another syntax are exercised
* by the walks only. */
std::vector<std::string> tool_call_texts() {
return {
"<tool_call>\n<function=bash>\n<parameter=command>\n"
@@ -292,9 +260,9 @@ std::vector<std::string> tool_call_texts() {
};
}
/* JSON schemas of the shapes response_format and tool arguments take, each with a document it
* admits, written the way a model writes one. The converter emits required properties before
* optional ones, and reads an empty schema as any object, so the documents do too. */
/* JSON schemas shaped like response_format and tool arguments, each with an admitted document as a
* model would write it. The converter puts required properties before optional ones and reads an
* empty schema as any object; the documents follow suit. */
struct SchemaCase { const char* name; const char* schema; std::vector<std::string> docs; };
std::vector<SchemaCase> schema_cases() {
@@ -384,8 +352,8 @@ uint64_t xorshift(uint64_t& s) {
return s;
}
/* A fresh copy of the grammar text: a trailing comment changes the program cache's key and not
* the grammar, so the compile and every mask start from nothing. */
/* A fresh copy of the grammar text: a trailing comment changes the program cache key but not the
* grammar, so the compile and every mask start cold. */
std::string fresh(const std::string& text) {
static int n = 0;
return text + "\n# rad-gbnf-check run " + std::to_string(++n) + "\n";
@@ -442,12 +410,11 @@ Replay replay(Run& run, GbnfGrammar& g, const std::vector<int32_t>& toks, const
return r;
}
/* Random walks through the grammar: each step drafts a window of up to three tokens, mostly from
* what the mask admits, masks every position of it, verifies it the way the engine does and
* accepts the verified prefix and one more. Returns the masks taken. */
/* Random walks: each step drafts up to three tokens (mostly admissible), masks every position,
* verifies as the engine does and accepts the verified prefix plus one. Returns the masks taken. */
int64_t walks(Run& run, const std::string& text, int n_walks, int n_steps, uint64_t seed,
const char* where) {
const RealView& v = *run.view;
const TokenView& v = *run.view;
const int32_t n_tok = v.n_tokens();
int64_t masks = 0;
for (int w = 0; w < n_walks; ++w) {
@@ -505,7 +472,7 @@ struct Totals {
void run_grammar(Run& base, Totals& tot, const std::string& label, const std::string& text,
const std::vector<std::string>& docs, int passes, int n_walks, int n_steps,
uint64_t seed) {
const RealView& v = *base.view;
const TokenView& v = *base.view;
std::printf("\n== %s: %zu bytes of GBNF\n", label.c_str(), text.size());
/* Compile from nothing. */
@@ -546,8 +513,7 @@ void run_grammar(Run& base, Totals& tot, const std::string& label, const std::st
texts.push_back(std::move(toks));
}
/* The timing pass, on the program just compiled: the first replay pass is the first request
* that ever used the grammar; later passes are warm. */
/* Timing pass on the program just compiled: the first replay pass is cold, later ones warm. */
Run run;
run.view = base.view;
run.oracle = OracleMode::Off;
@@ -590,8 +556,8 @@ void run_grammar(Run& base, Totals& tot, const std::string& label, const std::st
tot.cold_split.merge(run.cold_split);
tot.warm.merge(run.warm);
/* The oracle's pass, on a second program compiled from nothing, over the same replays and
* walks: every mask the timing pass computed is computed again here and compared. */
/* Oracle pass on a second cold program over the same replays and walks; every mask the
* timing pass computed is recomputed and compared. */
if (base.oracle == OracleMode::Off) return;
const std::string oracle_text = fresh(text);
Run orc;
@@ -634,18 +600,28 @@ int main(int argc, char** argv) {
if (i + 1 >= argc) { usage(); std::exit(2); }
return argv[++i];
};
auto num = [&](const char* flag, int64_t lo, int64_t hi) {
return rad_flag_int("rad-gbnf-check", flag, next().c_str(), lo, hi);
};
if (a == "--tokenizer") tok_path = next();
else if (a == "--template") tpl_path = next();
else if (a == "--tokenizer-config") cfg_path = next();
else if (a == "--schema") schema_files.push_back(next());
else if (a == "--gbnf") gbnf_files.push_back(next());
else if (a == "--walks") n_walks = std::atoi(next().c_str());
else if (a == "--walk-steps") n_steps = std::atoi(next().c_str());
else if (a == "--passes") passes = std::atoi(next().c_str());
else if (a == "--seed") seed = (uint64_t)std::strtoull(next().c_str(), nullptr, 10);
else if (a == "--walks") n_walks = (int)num(a.c_str(), 0, INT32_MAX);
else if (a == "--walk-steps") n_steps = (int)num(a.c_str(), 0, INT32_MAX);
else if (a == "--passes") passes = (int)num(a.c_str(), 0, INT32_MAX);
else if (a == "--seed") seed = (uint64_t)num(a.c_str(), 0, INT64_MAX);
else if (a == "--oracle") {
const std::string m = next();
oracle = m == "all" ? OracleMode::All : m == "off" ? OracleMode::Off : OracleMode::Cold;
if (m == "all") oracle = OracleMode::All;
else if (m == "off") oracle = OracleMode::Off;
else if (m == "cold") oracle = OracleMode::Cold;
else {
std::fprintf(stderr, "rad-gbnf-check: --oracle takes cold, all or off, not '%s'\n",
m.c_str());
return 2;
}
} else { usage(); return 2; }
}
if (tok_path.empty() || tpl_path.empty()) { usage(); return 2; }
@@ -655,8 +631,8 @@ int main(int argc, char** argv) {
"tokenizer_config.json";
}
/* The report prints every compile itself, so the engine's per-compile line is left out,
* and stdout is line-buffered so that a warning cannot land in the middle of a report line. */
/* The report prints compiles itself, so the engine's per-compile line is suppressed; stdout is
* line-buffered so warnings cannot land mid-line. */
rad::log_set_level(rad::Log::Warn);
std::setvbuf(stdout, nullptr, _IOLBF, 0);
@@ -668,7 +644,7 @@ int main(int argc, char** argv) {
}
auto vocab = std::make_shared<Vocab>();
if (vocab->load(std::move(vb)) < 0) return 2;
RealView view;
TokenView view;
if (view.init(vocab) < 0) return 2;
const double rss_vocab = rss_mib();
+18 -28
View File
@@ -1,14 +1,11 @@
/* rad-info -- print what a .rad contains.
*
* This is the tool you reach for when something is wrong, so it is written for reading: aligned
* columns, byte counts in human units, and every number that could mislead labelled with what it
* actually counts. It opens the container read-only and touches nothing else -- no plugins, no
* declare -- so it works on any container, whatever is installed beside it.
* Output is for reading: aligned columns, human byte units, and every count labelled with what it
* counts. The container is opened read-only with no plugins and no declare phase, so it works on
* any container regardless of what is installed.
*
* `--plugins` is the other question an operator asks when something is wrong: what the search path
* in $RADIANCE_HOME actually offers, and from which file. It loads the plugins exactly as the
* engine does and prints each one as it registered -- the libraries radiance ships beside any
* other, because they are found the same way.
* `--plugins` instead loads the plugins from $RADIANCE_HOME as the engine does and prints each as
* it registered, with the file it came from.
*/
#include "iface.h"
#include "format/encoding.h"
@@ -88,8 +85,7 @@ const char* tok_kind(uint32_t k) {
}
}
/* Escape a token's text for one line of a report. Byte-level BPE puts U+0120 and friends in
* there, and a raw newline in a column ruins the table. */
/* Escape a token's text for one report line (control characters, newlines), truncated at `cap`. */
std::string vis(const char* s, size_t cap = 40) {
std::string out;
for (const char* p = s; *p && out.size() < cap; ++p) {
@@ -189,9 +185,8 @@ void print_tensor_row(const RadFile& f, const RadFileEntry& e, const char* inden
}
}
/* The directory, grouped the way the format is organised: by layer, and within a layer by
* movement unit. The unit is what the mover transfers, so it is the number that matters, and it
* is printed even when --verbose is off. */
/* The directory, grouped by layer and then by movement unit (what the mover transfers). Unit sizes
* are printed even without --verbose. */
void print_directory(const RadFile& f, bool verbose) {
std::printf("\nweight directory (%lld entries, grouped by layer and movement unit)\n",
(long long)f.entry_count());
@@ -199,8 +194,7 @@ void print_directory(const RadFile& f, bool verbose) {
int64_t i = 0;
int64_t total_payload = 0;
/* By what the numbers ARE, which is the question a container answers -- and by which
* quantiser made them, which is the question a quality regression asks. */
/* Totals by encoding and by provenance (which quantiser made the weights). */
std::map<std::string, std::pair<int64_t, int64_t>> by_enc; /* entries, bytes */
std::map<std::string, std::pair<int64_t, int64_t>> by_prov;
@@ -234,13 +228,12 @@ void print_directory(const RadFile& f, bool verbose) {
if (i >= f.entry_count() || f.entry(i).layer != layer || f.entry(i).expert < 0) continue;
const RadFile::ExpertGroup* g = f.group_for_layer(layer);
if (!g) { ++i; continue; } /* validate() guarantees this cannot happen; be quiet if it does */
if (!g) { ++i; continue; } /* validate() rules this out */
std::printf("\n layer %-14d %3d expert(s) x %d slot(s) %11s unit: one expert\n",
layer, g->n_expert, g->n_slot,
humanb((int64_t)g->stride * g->n_expert).c_str());
/* base + id*stride is the whole point of the format, so print the two numbers that make
* it true rather than making the reader derive them. */
/* Experts are addressed as base + id * stride. */
std::printf(" addressing base %llu + id * %llu (payload %s, %s of it padding)\n",
(unsigned long long)g->base, (unsigned long long)g->stride,
humanb((int64_t)g->unit_bytes).c_str(),
@@ -298,8 +291,7 @@ void print_vocab(const RadFile& f) {
std::printf(" chat template %s\n", ct[0] ? fmt("%zu bytes", std::strlen(ct)).c_str() : "none");
if (v.h->n_steps) {
/* The chain, in declared order. rad-convert interprets tokenizer.json properly instead of
* hashing it against a hardcoded enum (spec §12), so this is what it decided. */
/* The chain in declared order, as rad-convert interpreted tokenizer.json (spec §12). */
std::printf(" chain (%u steps, in order)\n", v.h->n_steps);
for (uint32_t i = 0; i < v.h->n_steps; ++i) {
const RadVocabStep& s = v.steps[i];
@@ -324,11 +316,8 @@ void print_vocab(const RadFile& f) {
(long long)n[RAD_TT_BYTE]);
}
/* EVERY CONTROL AND USER-DEFINED TOKEN, WITH ITS ID. Thirty-odd lines, and they are the ones
* that decide where a turn ends -- which is a question that otherwise can only be answered by
* reading a generation log and guessing. A model that ends its turn on a token the container
* did not declare as eos or eot generates straight past it into a hallucinated next turn, and
* that failure reads as a rambling model rather than as a mislabelled token. */
/* Every control and user-defined token with its id: these decide where a turn ends. A model
* that ends its turn on a token not declared eos or eot runs on into a hallucinated next turn. */
if (v.tok_type && v.tok_text) {
std::printf(" control/user (the tokens a turn can end on; eos/eot marked)\n");
for (uint32_t i = 0; i < v.h->n_tokens; ++i) {
@@ -377,8 +366,8 @@ void print_profile(const RadFile& f, int top) {
std::printf(" ... %zu more (--profile 0 for all)\n", v.size() - (size_t)n);
}
/* Every plugin on the search path, one line each, in the order the loader registered it: what kind,
* what it calls itself, what it declares, and the file it came from. */
/* Every plugin on the search path in registration order: kind, name, what it declares, and its
* file. */
int print_plugins(const std::string& home) {
LoadedPlugins lp;
if (rad_tools_load_plugins(home, rad_hierarchy_from_env(), "", "", &lp) < 0) return 1;
@@ -425,7 +414,8 @@ int main(int argc, char** argv) {
else if (a == "-v" || a == "--verbose") verbose = true;
else if (a == "--meta") only_meta = true;
else if (a == "--vocab") only_vocab = true;
else if (a == "--profile") top = std::atoi(next("--profile"));
else if (a == "--profile") top = (int)rad_flag_int("rad-info", "--profile", next("--profile"),
0, INT32_MAX);
else if (a == "--recipe") only_recipe = true;
else if (a == "--plugins") plugins = true;
else if (a == "--home") home = next("--home");
+2250 -1873
View File
File diff suppressed because it is too large. Load diff
+26 -29
View File
@@ -1,14 +1,9 @@
/* rad-schemas -- print, and diff, the op schemas two or more kernel plugins declare.
*
* The first plugin in hierarchy order to declare an op FIXES its schema, and a later plugin
* declaring the same op differently is refused AT LOAD with both plugins named (spec §2.3). That
* rule is right -- arguments are positional, so two disagreeing schemas make the same call mean
* different things depending on which plugin won selection, and that is silent numerical garbage
* rather than a diagnosable failure.
*
* But "refused at load" is a poor place to find out, because the message names one op and the
* plugin author has to guess the rest. This prints all of them at once, so a new kernel plugin can
* be conformed to the vocabulary before it is ever loaded beside another.
* The first plugin in hierarchy order to declare an op fixes its schema; a later plugin declaring
* it differently is refused at load (spec §2.3), because arguments are positional. The loader names
* one op at a time; this prints every disagreement at once, so a new plugin can be checked against
* the vocabulary before it is loaded beside another.
*
* rad-schemas libref.so print one plugin's vocabulary
* rad-schemas libr4d.so libref.so diff them, in hierarchy order
@@ -87,13 +82,19 @@ int load(const char* path, Loaded* out) {
} /* namespace */
static const char kUsage[] =
"usage: rad-schemas <plugin.so> [more.so ...]\n\n"
"One plugin prints its vocabulary. Two or more are diffed in hierarchy order:\n"
"the first to declare an op fixes its schema, and the loader refuses any plugin\n"
"that disagrees (spec §2.3).\n";
int main(int argc, char** argv) {
if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
fputs(kUsage, stdout);
return 0;
}
if (argc < 2) {
fprintf(stderr,
"usage: rad-schemas <plugin.so> [more.so ...]\n\n"
"One plugin prints its vocabulary. Two or more diff them IN HIERARCHY ORDER --\n"
"the first to declare an op fixes its schema, and any disagreement below is what\n"
"the loader will refuse (spec 2.3).\n");
fputs(kUsage, stderr);
return 2;
}
@@ -111,7 +112,7 @@ int main(int argc, char** argv) {
return 0;
}
/* Every op anyone declares, and who declares it. */
/* Every op any plugin declares. */
std::set<std::string> all;
for (auto& p : pl) for (auto& [op, s] : p.ops) all.insert(op);
@@ -122,30 +123,26 @@ int main(int argc, char** argv) {
if (have.size() < 2) continue;
++shared;
const RadOpSchema* first = have[0]->ops.at(op);
const std::string fp = params_of(first), fo = operands_of(first);
std::vector<std::pair<std::string, std::string>> desc; /* (params, operands) */
for (auto* p : have)
desc.emplace_back(params_of(p->ops.at(op)), operands_of(p->ops.at(op)));
bool differs = false;
for (size_t i = 1; i < have.size(); ++i) {
const RadOpSchema* s = have[i]->ops.at(op);
if (params_of(s) != fp || operands_of(s) != fo) differs = true;
}
for (const auto& d : desc) differs = differs || d != desc[0];
if (!differs) continue;
++conflicts;
printf("%s\n", op.c_str());
for (auto* p : have) {
const RadOpSchema* s = p->ops.at(op);
const bool ok = params_of(s) == fp && operands_of(s) == fo;
printf(" %-16s %s params %s\n", p->name.c_str(), ok ? " " : "!",
params_of(s).c_str());
printf(" %-16s %s operands %s\n", "", ok ? " " : "!", operands_of(s).c_str());
for (size_t i = 0; i < have.size(); ++i) {
const char* mark = desc[i] == desc[0] ? " " : "!";
printf(" %-16s %s params %s\n", have[i]->name.c_str(), mark, desc[i].first.c_str());
printf(" %-16s %s operands %s\n", "", mark, desc[i].second.c_str());
}
printf("\n");
}
printf("%d op(s) declared by more than one plugin, %d disagree.\n", shared, conflicts);
if (conflicts)
printf("The loader refuses the WHOLE plugin on any one of these, so every row it\n"
"carries is unreachable until they agree. docs/OPS.md is the contract.\n");
printf("The loader refuses the whole plugin on any one of these, so none of its rows\n"
"is reachable until they agree. docs/OPS.md is the contract.\n");
return conflicts ? 1 : 0;
}
+24 -21
View File
@@ -1,20 +1,19 @@
/* rad-tokcheck -- hold the tokeniser to its references over real text, and time it.
/* rad-tokcheck -- checks the tokeniser against its references over real text, and times it.
*
* Three questions, each answered per corpus file:
* 1. Does the encoder produce the ids the reference encoder produces (tools/tokref: llama.cpp's
* splitters and std::regex, a string-keyed merge)? Any difference is printed with the ids
* and text around it.
* 2. Does it produce the ids HuggingFace tokenizers produces? Those are read from files made
* elsewhere (`tokenizer.encode(text, add_special_tokens=False).ids`, little-endian int32,
* one file per corpus file), so nothing here needs Python.
* 3. How fast is it: MB/s for both encoders, and what re-tokenising a growing conversation
* costs with the segment cache and without it -- the shape of an agent re-sending its whole
* history every turn.
* Per corpus file:
* 1. Compare ids with the reference encoder (tools/tokref: llama.cpp's splitters, std::regex, a
* string-keyed merge). A difference is printed with the surrounding ids and text.
* 2. Compare ids with HuggingFace tokenizers, read from pre-made files
* (`tokenizer.encode(text, add_special_tokens=False).ids`, little-endian int32, one file per
* corpus file), so no Python is needed here.
* 3. Time both encoders (MB/s), and re-tokenising a growing conversation with and without the
* segment cache, as when an agent re-sends its whole history every turn.
*
* Exits non-zero on any difference, so it can gate a change.
*/
#include "text/tokenizer.h"
#include "tokref.h"
#include "iface.h"
#include <algorithm>
#include <chrono>
@@ -143,9 +142,9 @@ int main(int argc, char** argv) {
else if (a == "--hf-dir") hf_dir = next();
else if (a == "--no-ref") ref = false;
else if (a == "--user") parse_special = false;
else if (a == "--turns") turns = std::atoi(next());
else if (a == "--repeat") repeat = std::max(1, std::atoi(next()));
else if (a == "--context") ctx = std::atoi(next());
else if (a == "--turns") turns = (int)rad_flag_int("rad-tokcheck", "--turns", next(), 0, INT32_MAX);
else if (a == "--repeat") repeat = (int)rad_flag_int("rad-tokcheck", "--repeat", next(), 1, INT32_MAX);
else if (a == "--context") ctx = (int)rad_flag_int("rad-tokcheck", "--context", next(), 0, INT32_MAX);
else if (!a.empty() && a[0] == '-') { std::fprintf(stderr, "rad-tokcheck: unknown option %s\n", a.c_str()); return 2; }
else args.push_back(a);
}
@@ -172,9 +171,8 @@ int main(int argc, char** argv) {
if (!read_file(args[f], &text)) { std::printf(" %s: cannot read\n", args[f].c_str()); ++bad; continue; }
std::printf(" %s: %zu bytes\n", args[f].c_str(), text.size());
/* The first encode of a file is reported apart from the best repeat: the vocab keeps what
* it learns about which tokens merge back to themselves, so a repeat is faster than the
* first sight of a text, and both numbers are real. */
/* The first encode is reported separately from the best repeat: the vocab caches which
* tokens merge back to themselves, so repeats are faster. */
std::vector<int32_t> ids;
double best = 1e30, first = 0;
for (int r = 0; r < repeat; ++r) {
@@ -225,7 +223,7 @@ int main(int argc, char** argv) {
if (turns > 0) {
const std::vector<std::string> prompts = conversation(*vocab, text, turns);
Tokenizer cached;
cached.init(vocab);
if (cached.init(vocab) < 0) { std::printf(" multi-turn: init failed\n"); ++bad; continue; }
cached.clear_cache();
double cold = 0, warm = 0, cold_last = 0, warm_last = 0, rtot = 0, rlast = 0;
size_t prompt_bytes = 0;
@@ -233,11 +231,16 @@ int main(int argc, char** argv) {
for (size_t k = 0; k < prompts.size(); ++k) {
std::vector<int32_t> a, b, r;
auto t0 = Clock::now();
tok.encode(prompts[k], a, false, true);
const int sa = tok.encode(prompts[k], a, false, true);
const double c = secs(t0);
t0 = Clock::now();
cached.encode(prompts[k], b, false, true);
const int sb = cached.encode(prompts[k], b, false, true);
const double w = secs(t0);
if (sa < 0 || sb < 0) {
std::printf(" turn %zu: encode failed\n", k);
same = false;
continue;
}
cold += c;
warm += w;
cold_last = c;
@@ -257,7 +260,7 @@ int main(int argc, char** argv) {
const Tokenizer::CacheStats cs = cached.cache_stats();
std::printf(" %zu turns, %.1f MB re-sent (last prompt %zu bytes): %s\n", prompts.size(),
prompt_bytes / 1e6, prompts.empty() ? 0 : prompts.back().size(),
same ? "cached ids identical to uncached on every turn" : "CACHED IDS DIFFER");
same ? "cached ids identical to uncached on every turn" : "cached ids differ");
std::printf(" uncached %9.1f ms total, last turn %8.2f ms\n", cold * 1e3, cold_last * 1e3);
std::printf(" cached %9.1f ms total, last turn %8.2f ms (%llu hits, %zu entries, %.1f MB)\n",
warm * 1e3, warm_last * 1e3, (unsigned long long)cs.hits, cs.entries, cs.bytes / 1e6);
+117 -147
View File
@@ -1,21 +1,15 @@
/* rad-tune -- benchmark every point of each kernel's declared space at the graph's ACTUAL shapes and write
* the cache the selector consults at declare.
/* rad-tune -- benchmark every point of each kernel's declared tuning space at the shapes the graph
* actually issues, and write the cache the selector consults at declare.
*
* Constraint matching finds a kernel that is CORRECT for a geometry. Within one kernel there are
* usually many tile configurations and the right one is a property of the shape and the machine --
* vllm-radiance ships moe-configs/ and fp8-configs/ for exactly this, hand-tuned per shape
* (spec §15). This tool is the one mechanism, and tunecache.h is the one format. The alternative
* is every plugin inventing its own tuning tool and its own file, and the engine being unable to
* say why a shape is slow.
* Constraint matching finds a correct kernel for a geometry; within it, the best tile configuration
* depends on shape and machine (spec §15). This tool is the single tuning mechanism and tunecache.h
* the single format, so plugins need no tuning tools of their own.
*
* It tunes THE SHAPES THIS MODEL ACTUALLY ISSUES, not a swept grid: declare already enumerated
* every (kernel, geometry) pair the graph will ever reach, per band, so Program::tune_requests is
* the exact work list. A sweep would measure shapes nothing runs and miss the one that matters.
* The work list is Program::tune_requests: every (kernel, geometry) pair the declared graph can
* reach, per band, rather than a swept grid.
*
* Two properties of the measurement loop: a candidate's time is the MEDIAN over reps rather than
* its best, because a best-of hides a candidate that is fast when the clock is up and slow
* otherwise; and the SPREAD is reported beside it, so a measurement taken across a clock ramp is
* visible rather than silently believed.
* A candidate's time is the median over reps, not the best (a best-of hides clock-dependent
* candidates), and the spread is reported so a measurement across a clock ramp is visible.
*/
#include "kfixture.h"
#include "opshapes.h"
@@ -53,9 +47,9 @@ void usage() {
" --max-tok N the max_tok declare is run at (default 8192)\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"
" --num-speculative-tokens N\n"
" draft depth to declare at; default is the container's own, which\n"
" is what puts the DRAFTER's kernels in the measured graph at all.\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"
" --dry-run list what would be measured and stop\n"
" -v, --verbose print every candidate, not just the winner\n"
" -h, --help\n");
@@ -67,32 +61,26 @@ struct DevBuf {
~DevBuf() { if (p) rad_dev_free(p, RAD_MEM_DEVICE); }
};
/* How far a candidate may sit from the defaults and still be the same computation. A different
* split-K count reduces in a different ORDER, and at K=5120 in fp32 that moves the last bits;
* 1e-3 relative sits two orders above what such a reorder costs, and far below a transposed tile
* or a dropped k slice, which are the failures this exists to catch. */
/* Maximum relative difference from the defaults. A different split-K count reorders the reduction
* and moves the last bits (at K=5120 in fp32); 1e-3 is two orders above that and far below a
* transposed tile or a dropped k slice. */
constexpr double kVariantTol = 1e-3;
/* THE CANDIDATES: every legal point in the kernel's declared space, at THIS geometry.
/* The candidates: every legal point of the kernel's declared space at this geometry, as the cross
* product of its axes (a hand-written list of points can silently have holes). `tune_valid` prunes
* points this geometry cannot run, e.g. a split that does not divide K; a pruned point is a skip,
* not a failure.
*
* A cross product, and that is exactly the point of declaring axes instead of listing
* combinations. A hand-written list of points over a multi-axis space has holes in it, and a hole
* is invisible from the outside: a ladder that skips a value silently runs the next tile up, so a
* shape with 40 rows of work gets a 64-row tile and nothing says so. A product has no holes.
*
* `tune_valid` prunes what this geometry cannot run -- a split that does not divide K, a block
* wider than the machine allows -- which is the half a product of independent lists cannot say.
* A pruned candidate is a SKIP and not a failure: a kernel may serve a subset of its own space.
*
* The first candidate is always the all-defaults point, so the comparison the caller makes is
* against what an untuned install would have run.
* The all-defaults point, the baseline an untuned install runs, is moved to index 0 and
* `*has_defaults` set. It is absent only when tune_valid pruned it.
*/
enum { kMaxCandidates = 4096 };
static std::vector<std::vector<std::pair<std::string, int64_t>>>
tune_candidates(const RadKernelInfo* k, const Geometry& g, int64_t* space_size) {
tune_candidates(const RadKernelInfo* k, const Geometry& g, int64_t* space_size,
bool* has_defaults) {
std::vector<std::vector<std::pair<std::string, int64_t>>> out;
*has_defaults = false;
if (!k || k->n_tunables <= 0) return out;
int64_t total = 1;
@@ -122,21 +110,19 @@ tune_candidates(const RadKernelInfo* k, const Geometry& g, int64_t* space_size)
out.push_back(point);
}
/* The all-defaults point first, so index 0 is always the baseline an untuned install runs.
* It is in the list by construction -- the loader refuses a default that is not one of the
* axis's own values -- unless tune_valid prunes it at this geometry, which is a kernel saying
* it cannot serve this shape on its defaults and is worth seeing rather than hiding. */
/* The loader requires each default to be one of its axis's values, so the all-defaults point
* is in the product unless tune_valid pruned it. */
for (size_t i = 0; i < out.size(); ++i) {
bool all_default = true;
for (int a = 0; a < k->n_tunables; ++a)
if (out[i][(size_t)a].second != k->tunables[a].deflt) { all_default = false; break; }
if (all_default) { std::swap(out[0], out[i]); break; }
if (all_default) { std::swap(out[0], out[i]); *has_defaults = true; break; }
}
return out;
}
/* Every OUT and INOUT operand's bytes, after one launch at the geometry `g` -- which CARRIES the
* candidate point, because a tuned value is an ordinary parameter. This is what a candidate is
* compared against the defaults with. */
/* 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,
@@ -159,9 +145,8 @@ int capture_outputs(const KernelRow& row, std::vector<RadTensor>& t,
if (row.info->launch(&a, stream) < 0) return RAD_E_SHAPE;
if (stream && rad_stream_sync(stream) < 0) return RAD_E_STATE;
/* SIZED FIRST, THEN COPIED. Growing the destination between async copies reallocates it while
* the earlier ones are still in flight, writing into a freed block -- which is a double-free
* at the next resize and a corrupted comparison before that. */
/* 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;
@@ -185,8 +170,8 @@ int capture_outputs(const KernelRow& row, std::vector<RadTensor>& t,
return RAD_OK;
}
/* The largest relative difference over the captured outputs, widened to f32 through the operand's
* own dtype -- a bf16 output compared as raw bytes would call every one-ulp rounding a failure. */
/* The largest relative difference over the captured outputs, widened to f32 through each operand's
* dtype. */
double max_rel_diff(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b,
const std::vector<OpdShape>& sh, const RadOpSchema* schema) {
if (a.size() != b.size() || a.empty()) return a.size() == b.size() ? 0.0 : 1.0;
@@ -209,9 +194,8 @@ double max_rel_diff(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b
den += (double)fa[(size_t)i] * (double)fa[(size_t)i];
}
const double rel = den > 0 ? std::sqrt(num / den) : (num > 0 ? 1.0 : 0.0);
/* A NaN is the largest disagreement there is, and `rel > worst` is false for it: taken
* as a maximum it would vanish and a candidate that writes NaN would agree with the
* defaults. Returned as it is, the caller's `!(err <= tol)` rejects it. */
/* Return NaN directly: `rel > worst` is false for it, so a max would drop it. The caller's
* `!(err <= tol)` rejects it. */
if (std::isnan(rel)) return rel;
if (rel > worst) worst = rel;
at += (size_t)bytes;
@@ -219,11 +203,9 @@ double max_rel_diff(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b
return worst;
}
/* One measurement, in microseconds per launch, at the geometry `g` -- which CARRIES the candidate
* point, because a tuned value is an ordinary parameter. Negative means the kernel refused the
* shape, which is information and not a failure: a kernel is allowed to serve a subset of its own
* cross product, and the entry point is where that is rejected (spec 2.1). tune_valid prunes what
* it can from the geometry alone; this is where the rest shows up. */
/* 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) {
@@ -231,9 +213,7 @@ double time_point(const KernelRow& row, std::vector<RadTensor>& t,
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;
/* THE SCRATCH IS DEVICE MEMORY TOO, for the same reason the operands are: a split-K GEMM
* writes its partial planes into it from the device, so a host allocation is an address the
* kernel cannot write. */
/* 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);
@@ -246,19 +226,13 @@ double time_point(const KernelRow& row, std::vector<RadTensor>& t,
}
}
/* A warm launch first, and its status is the one that decides whether this candidate serves the
* shape at all. Timing a launch that returns negative measures the rejection. */
/* 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;
/* THE CLOCK STOPS AFTER THE DEVICE DOES. Every launch here is ASYNCHRONOUS, so enqueueing
* `iters` of them and reading the clock without the sync below measures the host's submission
* cost and nothing else: sub-microsecond, and flat across every shape in the table -- a 16-row
* GEMM and a 2048-row one land within a few percent of each other, orders of magnitude below
* the memory bound of either. Without the sync the tuner picks its winners out of submission
* noise, and a cache full of numbers that cannot happen is worse than no cache, because
* someone reads it. */
/* 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) {
@@ -293,25 +267,32 @@ int main(int argc, char** argv) {
std::exit(2); }
return argv[++i];
};
auto num = [&](const char* w, int64_t lo, int64_t hi) {
return rad_flag_int("rad-tune", w, next(w), lo, hi);
};
if (a == "-h" || a == "--help") { usage(); return 0; }
else if (a == "-m" || a == "--model") model = next("--model");
else if (a == "--home") home = next("--home");
else if (a == "--kernels") hierarchy = rad_split_list(next("--kernels"));
else if (a == "--op") op_filter = next("--op");
else if (a == "--machine") machine = next("--machine");
else if (a == "--reps") reps = std::atoi(next("--reps"));
else if (a == "--iters") iters = std::atoi(next("--iters"));
else if (a == "--max-tok") max_tok = std::atoll(next("--max-tok"));
else if (a == "--tp") tp = std::atoi(next("--tp"));
else if (a == "--num-speculative-tokens") spec = std::atoi(next("--num-speculative-tokens"));
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 == "--tp") tp = (int)num("--tp", 1, INT32_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");
spec = std::string(v) == "auto"
? -1 : (int)rad_flag_int("rad-tune", "--num-speculative-tokens", v, 0,
INT32_MAX);
}
else if (a == "--dry-run") dry = true;
else if (a == "-v" || a == "--verbose") verbose = true;
else { std::fprintf(stderr, "rad-tune: unrecognised argument '%s'. Try --help.\n",
a.c_str()); return 2; }
}
if (model.empty()) { usage(); return 2; }
if (reps < 1 || iters < 1) { std::fprintf(stderr, "rad-tune: --reps and --iters must be >= 1\n");
return 2; }
RadFile f;
if (f.open(model.c_str()) < 0) return 1;
@@ -347,12 +328,8 @@ int main(int argc, char** argv) {
for (auto& s : kv) vp.push_back(s.c_str());
meta.n_kv = (int)kk.size(); meta.kv_key = kp.data(); meta.kv_val = vp.data();
/* THE GRAPH HAS TO BE THE ONE THE DEPLOYMENT RUNS, or the shapes measured are not the shapes
* served. Two things decide that: the tensor-parallel width, which HALVES every sharded N, and
* the speculative depth, which is what puts the drafter in the graph at all. A declare at
* world_size 1 and max_spec 0 measures a program no `--tp 2` serve ever runs, with no drafter
* kernels in it -- and the drafter's shapes appear in no other model's tuning table either,
* so nothing else would cover them. */
/* Declare the graph the deployment runs: the tensor-parallel width sets every sharded N, and
* 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;
RadArchProbe probe{};
@@ -360,11 +337,9 @@ int main(int argc, char** argv) {
ctx.max_spec = spec >= 0 ? spec : probe.draft_depth;
ctx.max_seqs = 256; ctx.max_ctx = meta.n_ctx_train; ctx.scope = "";
/* EVERY RANK DECLARES AT ONCE, on its own thread and its own device, exactly as Engine does
* and for the reason stated there: kernel init() runs from declare, and a collective's init is
* a RENDEZVOUS -- libr4d's all-reduce publishes this rank's peer scratch pointer and then
* waits for the others. Declaring rank 0 alone at world_size 2 does not fail; it HANGS. Only
* rank 0's program is kept, because that is the one whose shapes get measured. */
/* 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;
{
std::vector<Program> progs((size_t)tp);
@@ -392,9 +367,8 @@ int main(int argc, char** argv) {
if (machine.empty()) machine = rad_machine_key();
/* Read from the first home on the search path that has a cache for this machine, written to
* the first home on it: an installation's cache is the starting point, and the operator's own
* home is where the measurements land. */
/* Load from the first home on the search path with a cache for this machine; save to the
* first home on the path. */
const std::string rel = TuneCache::rel_path(machine);
const std::string src = rad_home_file(home, rel);
const std::string save_home = rad_home_dirs(home).front();
@@ -415,16 +389,12 @@ int main(int argc, char** argv) {
return nullptr;
};
/* An op's schema, to size operands. tune_requests carries the kernel and the geometry but not
* the op's operand list, so it is looked up by the kernel's own op name. */
/* tune_requests lacks the operand list, so schemas are looked up by the kernel's op name. */
int measured = 0, skipped = 0, single = 0;
std::map<std::string, int> skip_why;
/* ONE STREAM FOR THE WHOLE RUN, and the measurement depends on having it: launching on the
* null stream and reading the clock times the host's submission and not the device's work.
* On the no-ROCm build the device layer is a host stub: the allocations are host memory, the
* launches are synchronous, and the sync is a no-op, so this path is the same shape either
* way rather than a second one. */
/* 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());
@@ -441,14 +411,18 @@ int main(int argc, char** argv) {
const std::string op = row->info->op;
if (!op_filter.empty() && op.rfind(op_filter, 0) != 0) continue;
/* THE CANDIDATE LIST IS THE DECLARED SPACE, pruned by the kernel's own tune_valid. A row
* with no axes has nothing to choose between: its launch is its only instantiation and an
* untuned install is therefore already running it, so writing a row for it would be a
* measurement nobody consults. */
/* A kernel with at most one candidate has nothing to choose; no row is written. */
int64_t space = 0;
const auto cands = tune_candidates(row->info, tr.geom, &space);
bool has_defaults = false;
const auto cands = tune_candidates(row->info, tr.geom, &space, &has_defaults);
const int n_var = (int)cands.size();
if (n_var <= 1) { ++single; continue; }
if (!has_defaults) {
skip_why[tr.plugin + "/" + tr.kernel + " (tune_valid rejects the defaults: no "
"reference to check candidates against)"]++;
++skipped;
continue;
}
const RadOpSchema* schema = reg.schema(op);
if (!schema) { skip_why[op + " (no schema)"]++; ++skipped; continue; }
@@ -458,9 +432,21 @@ int main(int argc, char** argv) {
for (const char* k : { "M", "q_len" }) if (tr.geom.get_i(k, &mv)) { M = (int64_t)mv; break; }
if (M <= 0) M = 1;
/* Operand shapes as rad-kbench takes them: the reference library's description (which
* defines the op), then the kernel's own, then the fallback table in opshapes.h. */
std::vector<OpdShape> sh;
if (rad_operand_shapes(op, tr.geom, schema->n_operands, M, &sh) < 0) {
skip_why[op + " (no shape recipe; see tools/opshapes.h)"]++;
int shst = RAD_E_UNSUPPORTED;
for (const Plugin& p : reg.plugins()) {
if (p.kind != RAD_PLUGIN_KERNEL || !p.reference) continue;
if (const KernelRow* rr = reg.select_in(p.name, op, tr.geom, RAD_DOMAIN_HOST))
shst = rad_operand_shapes_hook(rr->info, tr.geom, schema->n_operands, &sh);
break;
}
if (shst < 0) shst = rad_operand_shapes_hook(row->info, tr.geom, schema->n_operands, &sh);
if (shst < 0) shst = rad_operand_shapes(op, tr.geom, schema->n_operands, M, &sh);
if (shst < 0) {
skip_why[op + " (neither the reference nor the kernel describes its operands, and "
"tools/opshapes.h has no recipe)"]++;
++skipped;
continue;
}
@@ -472,14 +458,9 @@ int main(int argc, char** argv) {
continue;
}
/* THE INPUTS ARE DRAWN BY kf_draw, THE SAME DRAW rad-kbench CHECKS WITH, and that is what
* puts each operand inside the domain its recipe states. A length is a constant and not a
* draw: `seqused` is the context an attention reads, and drawn as an index into the
* previous operand's rows it is a context of nothing, which is where every `splits`
* candidate would be timed. Cumulative lengths are the batch's shape, a scatter's
* destinations are distinct and a block table indexes its own range. A candidate timed
* outside that domain is timed on work the model never hands it, and the winner is cached
* for the work it does. */
/* 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) and candidates are timed on realistic work. */
std::vector<KfOperand> kop(sh.size());
for (size_t k = 0; k < sh.size(); ++k) {
KfOperand& d = kop[k];
@@ -491,19 +472,17 @@ int main(int argc, char** argv) {
d.is_index = sh[k].is_index;
d.idx_unique = sh[k].idx_unique;
d.idx_cu = sh[k].idx_cu;
d.idx_prefix = sh[k].idx_prefix;
d.idx_history = sh[k].idx_history;
d.idx_max = sh[k].idx_max;
d.idx_const = sh[k].idx_const;
d.fill_chunk = sh[k].fill_chunk;
}
const int64_t vocab_rows = kf_vocab_rows(kop);
/* One set of buffers, reused across candidates: they must see the same bytes or the
* comparison is between two shapes as much as between two tilings.
*
* ON THE DEVICE. `store` is the host-side draw and only ever the source of a copy; what
* goes into RadTensor::data is the device allocation. Handing a device kernel a host
* address here does not announce itself -- without a synchronisation point nothing reports
* it at all -- so the two must not be confused. */
/* 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());
@@ -527,18 +506,15 @@ int main(int argc, char** argv) {
if (!ok) { skip_why[op + " (an operand has a plugin-private dtype the core cannot "
"size)"]++; ++skipped; continue; }
/* ONE GEOMETRY PER CANDIDATE, and it is the ONLY way the point reaches the kernel: the
* core does exactly this at issue, appending the chosen values to the resolved geometry so
* a launch reads `sk` with the same rad_args_geti() it reads `M` with. Built once, up
* front, so the measure loop below is a pure timing loop. */
/* 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`. */
std::vector<Geometry> gv((size_t)n_var);
for (int v = 0; v < n_var; ++v) {
gv[(size_t)v] = tr.geom;
for (const auto& kv : cands[(size_t)v]) gv[(size_t)v].set_i(kv.first.c_str(), kv.second);
}
/* Each candidate is timed over `reps` reps and reported as the median, with the spread
* kept beside it so a measurement taken across a clock ramp is visible. */
/* Median over `reps`, with the spread. */
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;
@@ -546,31 +522,27 @@ int main(int argc, char** argv) {
spread[(size_t)v] = sp;
}
/* ---- AND EACH ONE HAS TO AGREE WITH THE DEFAULTS BEFORE IT CAN WIN ON SPEED.
/* ---- each candidate must agree with the defaults before it can win on speed.
*
* A candidate is a tile configuration, and no other check in this tree exercises one past
* the defaults -- numeric selftests launch the first arm. So without this comparison a
* point that computes the wrong answer quickly is a point this tool crowns, and the cache
* is consulted at declare: the model then serves wrong numbers with nothing to say so. The
* failure is not loud either. A tuned arm that is subtly wrong shows up as degraded output
* quality -- lost speculative acceptance, say -- rather than as an error.
*
* CANDIDATE 0 IS THE ALL-DEFAULTS POINT, guaranteed by tune_candidates, and it is the
* reference because it is what an untuned install runs (spec §15) -- so "agrees with the
* defaults" is exactly the property that makes the cache safe to enable. The tolerance is
* loose, because a different split-K count reduces in a different ORDER and that moves the
* last bits legitimately; what it catches is a point that is wrong, not one that rounds
* differently. */
* No other check exercises non-default tile configurations, and a subtly wrong winner
* would be served from the cache, showing up only as degraded output quality. Candidate 0,
* the all-defaults point (what an untuned install runs, spec §15), is the reference.
* 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);
for (int v = 0; v < n_var; ++v) {
if (best_us[0] <= 0 || capture_outputs(*row, t, gv[0], schema, sh, stream, &ref) < 0) {
skip_why[tr.plugin + "/" + tr.kernel + " (the defaults refused the shape: no "
"reference to check candidates against)"]++;
++skipped;
continue;
}
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) {
best_us[(size_t)v] = (double)RAD_E_STATE;
continue;
}
if (v == 0) { ref = std::move(got); continue; }
verr[(size_t)v] = max_rel_diff(ref, got, sh, schema);
if (!(verr[(size_t)v] <= kVariantTol)) best_us[(size_t)v] = (double)RAD_E_SHAPE;
}
@@ -581,7 +553,7 @@ int main(int argc, char** argv) {
win = v;
if (win < 0) {
std::printf(" %-22s %-46s NO CANDIDATE SERVED IT (%s/%s, %d tried of %lld)\n",
std::printf(" %-22s %-46s no candidate served it (%s/%s, %d tried of %lld)\n",
op.c_str(), tr.geom.str().c_str(), tr.plugin.c_str(), tr.kernel.c_str(),
n_var, (long long)space);
++skipped;
@@ -598,7 +570,7 @@ int main(int argc, char** argv) {
nm.c_str(), best_us[(size_t)v], spread[(size_t)v], verr[(size_t)v],
v == win ? " <-" : "");
else if (!(verr[(size_t)v] <= kVariantTol))
std::printf(" %-32s REJECTED: disagrees with the defaults by %.3g\n",
std::printf(" %-32s rejected: disagrees with the defaults by %.3g\n",
nm.c_str(), verr[(size_t)v]);
else
std::printf(" %-32s refused: %s\n", nm.c_str(),
@@ -609,10 +581,8 @@ int main(int argc, char** argv) {
tr_out.kernel = tr.kernel;
tr_out.plugin = tr.plugin;
tr_out.choice = wname;
/* THE KEY IS THE GEOMETRY WITHOUT THE POINT. `tr.geom` is the untouched instantiation --
* the dims the caller asked for -- and the chosen axes live in `choice`. Keying on `gv`
* instead would write a row the selector can never find, because at issue it looks the
* instantiation up BEFORE it knows what to choose. */
/* Key on the geometry without the point (the chosen axes are in `choice`): the selector
* looks the instantiation up before it knows what to choose. */
tr_out.geom = tr.geom_key;
tr_out.us = best_us[(size_t)win];
tr_out.measured = TuneCache::now_iso8601();
+197 -165
View File
@@ -1,16 +1,14 @@
/* tokref.cpp -- a reference encoder: llama.cpp's splitters, std::regex and a string-keyed merge.
*
* A REFERENCE, not a fallback: core/ does not link it. It runs a `Split` through
* llama.cpp's unicode_regex_split -- a hand-written splitter for the patterns llama.cpp knows, and
* std::regex over a category-collapsed copy of the text for every other one -- and it merges with
* a string-keyed bigram queue. That is an implementation independent of everything in
* core/text/tokenizer_regex.cpp and tokenizer_bpe.cpp, which is what makes it worth comparing
* against: tokenizer_test holds core/text's encoder to it id for id, and rad-tokcheck does the
* same over large corpora. Where the two disagree because this one is wrong -- see tokref.h -- the
* test says so case by case rather than excluding the input.
* A reference, not a fallback; core/ does not link it. A `Split` goes through llama.cpp's
* unicode_regex_split (hand-written splitters for known patterns, std::regex over a
* category-collapsed copy of the text otherwise), and merging uses a string-keyed bigram queue.
* It is independent of core/text/tokenizer_regex.cpp and tokenizer_bpe.cpp. Known divergences are
* listed in tokref.h.
*/
#include "tokref.h"
#include "text/tokenizer_ucd.h"
#include "text/unicode_norm.h"
#include "llama/src/unicode.h"
@@ -78,32 +76,21 @@ void replace_all(std::string& s, std::string_view from, std::string_view to) {
/* ================================================================== the pre-tokeniser regex
*
* WHICH PATTERNS ARE HANDLED STRUCTURALLY AND WHICH FALL THROUGH -- read this before changing
* anything below it.
* Structural patterns: vendor/llama/src/unicode.cpp has hand-written splitters for the patterns
* that ship on models (GPT-2, Llama-3, Qwen2, Qwen3.5, Kimi-K2, the AFMoE digit rule and
* "[^\n]+|[\n]+"). They are codepoint-class state machines without backtracking, correct on
* lookaheads such as `\s+(?!\S)`. `unicode_regex_split` picks one by exact pattern string.
*
* llama.cpp carries hand-written splitters for the patterns that actually ship on models, in
* vendor/llama/src/unicode.cpp: the GPT-2 pattern, the Llama-3 pattern, the Qwen2 pattern, the
* Qwen3.5 pattern, Kimi-K2, the AFMoE digit rule, and "[^\n]+|[\n]+". Those are STRUCTURAL: a
* codepoint-class state machine, no backtracking, and correct on the lookahead constructs
* (`\s+(?!\S)`) that a general engine gets wrong or slow. `unicode_regex_split` dispatches on the
* pattern string and picks one of them when it matches.
*
* Everything else FALLS THROUGH to std::regex over a collapsed representation of the text, where
* each non-ASCII codepoint is replaced by one byte standing for its unicode category. That is
* llama.cpp's trick and it is what makes `\p{L}` work under a std::regex that has no idea what
* `\p{L}` is. Its limits, stated plainly, because they are real:
* Everything else falls through to std::regex over a copy of the text where each non-ASCII
* codepoint is replaced by one byte for its Unicode category, which makes `\p{L}` work. Limits:
* - a pattern mixing `\p{...}` with a non-ASCII literal is refused, not approximated;
* - possessive quantifiers and atomic groups are not ECMAScript and are not supported;
* - possessive quantifiers and atomic groups (not ECMAScript) are unsupported;
* - std::regex backtracks, so a pathological pattern is slow rather than wrong.
* A model whose pre-tokeniser needs more than that gets a hand-written splitter here, next to
* the others, and the .rad still declares the pattern so the decision stays visible.
* A model that needs more gets a hand-written splitter.
*
* The one rewrite we do apply before dispatching is the case-insensitive contraction group.
* tokenizer.json writes `(?i:'s|'t|'re|'ve|'m|'ll|'d)`; ECMAScript has no inline flag group, so
* llama.cpp expands it to explicit classes and keys its structural splitters off the EXPANDED
* form. Rewriting here is what lets a pattern read straight out of tokenizer.json reach the
* structural splitter instead of the fallback -- which for Qwen is the difference between a
* correct split and a merely plausible one. */
* One rewrite is applied before dispatch: tokenizer.json's `(?i:'s|'t|'re|'ve|'m|'ll|'d)` becomes
* explicit classes, since ECMAScript has no inline flag group and llama.cpp keys its structural
* splitters off the expanded form. Without it Qwen's pattern would miss its structural splitter. */
const char* k_ci_contractions_in = "(?i:'s|'t|'re|'ve|'m|'ll|'d)";
const char* k_ci_contractions_out = "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])";
@@ -113,13 +100,9 @@ std::string canonicalise_pattern(const std::string& p) {
return out;
}
/* Does `unicode_regex_split` have a structural splitter for this pattern? Used only for the
* diagnostic line, so a slow model is diagnosable without a profiler.
*
* IT MUST CANONICALISE FIRST, for the same reason apply_split does: comparing the raw pattern
* reports "[std::regex fallback]" for a pattern the split path does in fact handle structurally,
* and a diagnostic that claims a correctness problem where there is none is worse than no
* diagnostic at all. */
/* Whether `unicode_regex_split` has a structural splitter for this pattern (diagnostics only).
* Canonicalises first, as apply_split does, or a structurally handled pattern would be reported as
* a std::regex fallback. */
bool pattern_is_structural(const std::string& raw) {
const std::string p = canonicalise_pattern(raw);
static const char* k_structural[] = {
@@ -137,17 +120,14 @@ bool pattern_is_structural(const std::string& raw) {
}
/* --- normalisers ------------------------------------------------------------------------- */
/* A literal Replace is a plain find-and-replace. A regex Replace goes through std::regex, which
* is acceptable HERE and not in the pre-tokeniser: normalisers run once over the whole prompt
* rather than once per candidate split, and the patterns that show up in practice
* (`\s+` -> ` `, `` -> `_`) are trivial. */
/* A literal Replace is find-and-replace; a regex Replace uses std::regex, acceptable here because
* normalisers run once per prompt and real patterns (`\s+` -> ` `, `` -> `_`) are trivial. */
void apply_replace(std::string& text, const VocabStep& s) {
if (s.flags & 1) {
try {
text = std::regex_replace(text, std::regex(s.arg0), s.arg1);
} catch (const std::regex_error& e) {
/* Refusing to normalise is worse than a slightly wrong normalisation only if you
* think a silent difference is cheap. Say it, once, and leave the text alone. */
/* Warn and leave the text unchanged. */
RAD_WARN("tokenizer: Replace pattern '%s' did not compile (%s); step skipped",
s.arg0.c_str(), e.what());
}
@@ -171,8 +151,7 @@ void apply_norm(std::string& text, const VocabStep& s) {
break;
}
case RAD_NORM_STRIP: {
/* Whitespace by the unicode definition, not isspace(): a non-breaking space in a
* pasted prompt is whitespace to HuggingFace and would not be to isspace(). */
/* Unicode whitespace, not isspace(): HuggingFace strips e.g. a non-breaking space. */
std::vector<uint32_t> cpts = unicode_cpts_from_utf8(text);
size_t a = 0, b = cpts.size();
if (s.flags & 1) while (a < b && unicode_cpt_flags_from_cpt(cpts[a]).is_whitespace) ++a;
@@ -203,8 +182,7 @@ void apply_split(std::vector<std::string>& words, const VocabStep& s) {
out.reserve(words.size() * 2);
for (const std::string& w : words) {
if (w.empty()) continue;
/* byte_encode=false: ByteLevel is its own declared step and applying it here as well
* would encode twice. */
/* byte_encode=false: ByteLevel is its own declared step. */
std::vector<std::string> parts;
try {
parts = unicode_regex_split(w, exprs, /*byte_encode=*/false);
@@ -212,9 +190,8 @@ void apply_split(std::vector<std::string>& words, const VocabStep& s) {
RAD_ERR("tokenizer: Split('%s') failed: %s", s.arg0.c_str(), e.what());
parts = { w };
}
/* Behaviour only changes what happens to the DELIMITERS, and the patterns that ship on
* real models are "Isolated" with a pattern that matches the pieces themselves, so
* every part is kept. Removed drops empty parts only, which is already the case. */
/* Every behaviour is treated as Isolated (see tokref.h): behaviour only affects
* delimiters, and shipped patterns are Isolated and match the pieces themselves. */
for (std::string& p : parts) if (!p.empty()) out.push_back(std::move(p));
}
words.swap(out);
@@ -228,9 +205,8 @@ void apply_bytelevel(std::vector<std::string>& words, const VocabStep& s) {
words[0].insert(words[0].begin(), ' ');
}
if (use_regex) {
/* HuggingFace's ByteLevel carries the GPT-2 pattern inside it. rad-convert normally
* splits that out into an explicit Split step so the chain reads as what it does, but a
* chain that declares it inline still has to work. */
/* HuggingFace's ByteLevel can carry the GPT-2 pattern inline. rad-convert normally emits
* it as an explicit Split step, but the inline form must still work. */
VocabStep split;
split.kind = RAD_PRE_SPLIT;
split.arg0 = "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)";
@@ -240,14 +216,14 @@ void apply_bytelevel(std::vector<std::string>& words, const VocabStep& s) {
for (std::string& w : words) w = byte_encode(w);
}
void apply_metaspace(std::vector<std::string>& words, const VocabStep& s) {
void apply_metaspace(std::vector<std::string>& words, const VocabStep& s, bool at_start) {
const std::string rep = s.arg0.empty() ? std::string(k_metaspace) : s.arg0;
const int64_t prepend = s.iarg; /* 0 never, 1 first, 2 always */
const bool split = (s.flags & 1) != 0;
for (size_t i = 0; i < words.size(); ++i) {
std::string& w = words[i];
if (prepend == 2 || (prepend == 1 && i == 0)) {
if (prepend == 2 || (prepend == 1 && i == 0 && at_start)) {
if (w.empty() || w.compare(0, 1, " ") != 0) w.insert(0, " ");
}
replace_all(w, " ", rep);
@@ -267,25 +243,118 @@ void apply_metaspace(std::vector<std::string>& words, const VocabStep& s) {
words.swap(out);
}
/* Whitespace pre-tokeniser: HuggingFace's is the regex \w+|[^\w\s]+ with Isolated behaviour.
* Written structurally because \w is locale-dependent in std::regex and is not there. */
void apply_whitespace(std::vector<std::string>& words) {
/* Membership in one of tokenizer_ucd.h's sorted range tables. */
bool in_ranges(const ucd::CpRange* r, size_t n, uint32_t c) {
size_t lo = 0, hi = n;
while (lo < hi) {
const size_t mid = (lo + hi) / 2;
if (r[mid].last < c) lo = mid + 1;
else if (r[mid].first > c) hi = mid;
else return true;
}
return false;
}
uint32_t gc_of(uint32_t c) {
size_t lo = 0, hi = ucd::k_gc_runs_n;
while (hi - lo > 1) {
const size_t mid = (lo + hi) / 2;
if (ucd::k_gc_runs[mid].first <= c) lo = mid; else hi = mid;
}
return ucd::k_gc_runs[lo].gc;
}
bool is_space(uint32_t c) { return in_ranges(ucd::k_white_space, ucd::k_white_space_n, c); }
/* Rust's char::is_ascii_punctuation || char::is_punctuation (a P* category), the test
* HuggingFace's Punctuation and BertPreTokenizer split on. */
bool is_hf_punct(uint32_t c) {
if ((c >= 0x21 && c <= 0x2F) || (c >= 0x3A && c <= 0x40) || (c >= 0x5B && c <= 0x60) ||
(c >= 0x7B && c <= 0x7E))
return true;
const uint32_t g = gc_of(c);
return g >= ucd::Pc && g <= ucd::Po;
}
/* Rust's char::is_numeric, the test Digits splits on: Nd, Nl, No. */
bool is_numeric(uint32_t c) {
const uint32_t g = gc_of(c);
return g == ucd::Nd || g == ucd::Nl || g == ucd::No;
}
/* NormalizedString::split with a character predicate: every character it accepts is a delimiter
* of its own, the runs between them are the other parts, and `behavior` folds the two. */
template <class Pred>
void split_chars(std::vector<std::string>& words, Pred is_delim, int behavior) {
std::vector<std::string> out;
for (const std::string& w : words) {
std::vector<std::pair<std::string, bool>> parts;
for (uint32_t c : unicode_cpts_from_utf8(w)) {
const bool d = is_delim(c);
if (!d && !parts.empty() && !parts.back().second) parts.back().first += unicode_cpt_to_utf8(c);
else parts.push_back({ unicode_cpt_to_utf8(c), d });
}
std::vector<std::string> kept;
bool prev = false;
switch (behavior) {
case SPLIT_REMOVED:
for (auto& p : parts) if (!p.second) kept.push_back(p.first);
break;
case SPLIT_MERGED_PREV:
for (auto& p : parts) {
if (p.second && !prev && !kept.empty()) kept.back() += p.first;
else kept.push_back(p.first);
prev = p.second;
}
break;
case SPLIT_MERGED_NEXT:
for (size_t k = parts.size(); k-- > 0; ) {
if (parts[k].second && !prev && !kept.empty()) kept.back() = parts[k].first + kept.back();
else kept.push_back(parts[k].first);
prev = parts[k].second;
}
std::reverse(kept.begin(), kept.end());
break;
case SPLIT_CONTIGUOUS:
for (auto& p : parts) {
if (p.second == prev && !kept.empty()) kept.back() += p.first;
else kept.push_back(p.first);
prev = p.second;
}
break;
default:
for (auto& p : parts) kept.push_back(p.first);
break;
}
for (std::string& k : kept) if (!k.empty()) out.push_back(std::move(k));
}
words.swap(out);
}
/* Rust's regex \w, which HuggingFace's Whitespace uses: Alphabetic (letters, Nl, and the
* circled and squared Latin letters among the symbols), marks, Nd, Pc and the two joiners. */
bool is_rust_word(uint32_t c) {
const uint32_t g = gc_of(c);
return g <= ucd::Lo || g == ucd::Nl || (g >= ucd::Mn && g <= ucd::Me) || g == ucd::Nd ||
g == ucd::Pc || c == 0x200C || c == 0x200D || (c >= 0x24B6 && c <= 0x24E9) ||
(c >= 0x1F130 && c <= 0x1F149) || (c >= 0x1F150 && c <= 0x1F169) ||
(c >= 0x1F170 && c <= 0x1F189);
}
/* HuggingFace's Whitespace: the matches of \w+|[^\w\s]+, everything else removed. Alternation is
* leftmost-first, so a run of \w is taken first, then a run of what is neither \w nor \s. */
void apply_whitespace_words(std::vector<std::string>& words) {
std::vector<std::string> out;
for (const std::string& w : words) {
const std::vector<uint32_t> cpts = unicode_cpts_from_utf8(w);
auto word = [](uint32_t c) { return is_rust_word(c); };
auto other = [](uint32_t c) { return !is_rust_word(c) && !is_space(c); };
size_t i = 0;
while (i < cpts.size()) {
const auto f = unicode_cpt_flags_from_cpt(cpts[i]);
if (f.is_whitespace) { ++i; continue; }
const bool word = f.is_letter || f.is_number || cpts[i] == '_';
size_t j = i;
while (j < cpts.size()) {
const auto g = unicode_cpt_flags_from_cpt(cpts[j]);
if (g.is_whitespace) break;
const bool wj = g.is_letter || g.is_number || cpts[j] == '_';
if (wj != word) break;
++j;
}
if (word(cpts[i])) while (j < cpts.size() && word(cpts[j])) ++j;
else if (other(cpts[i])) while (j < cpts.size() && other(cpts[j])) ++j;
if (j == i) { ++i; continue; }
std::string piece;
for (size_t k = i; k < j; ++k) piece += unicode_cpt_to_utf8(cpts[k]);
out.push_back(std::move(piece));
@@ -295,47 +364,18 @@ void apply_whitespace(std::vector<std::string>& words) {
words.swap(out);
}
void apply_whitespace(std::vector<std::string>& words, const VocabStep& s) {
if (s.flags == kPreWhitespace) { apply_whitespace_words(words); return; }
split_chars(words, is_space, SPLIT_REMOVED);
if (s.flags == kPreBert) split_chars(words, is_hf_punct, SPLIT_ISOLATED);
}
void apply_punctuation(std::vector<std::string>& words, const VocabStep& s) {
const int64_t behavior = s.iarg;
std::vector<std::string> out;
for (const std::string& w : words) {
const std::vector<uint32_t> cpts = unicode_cpts_from_utf8(w);
std::string acc;
for (uint32_t c : cpts) {
const auto f = unicode_cpt_flags_from_cpt(c);
const bool punct = f.is_punctuation || f.is_symbol;
if (punct) {
if (!acc.empty()) { out.push_back(acc); acc.clear(); }
if (behavior != SPLIT_REMOVED) out.push_back(unicode_cpt_to_utf8(c));
} else {
acc += unicode_cpt_to_utf8(c);
}
}
if (!acc.empty()) out.push_back(acc);
}
words.swap(out);
split_chars(words, is_hf_punct, (int)s.iarg);
}
void apply_digits(std::vector<std::string>& words, const VocabStep& s) {
const bool individual = (s.flags & 1) != 0;
std::vector<std::string> out;
for (const std::string& w : words) {
const std::vector<uint32_t> cpts = unicode_cpts_from_utf8(w);
std::string acc;
bool acc_digit = false;
for (uint32_t c : cpts) {
const bool d = unicode_cpt_flags_from_cpt(c).is_number;
if (acc.empty()) { acc_digit = d; acc += unicode_cpt_to_utf8(c); continue; }
if (d != acc_digit || (d && individual)) {
out.push_back(acc);
acc.clear();
acc_digit = d;
}
acc += unicode_cpt_to_utf8(c);
}
if (!acc.empty()) out.push_back(acc);
}
words.swap(out);
split_chars(words, is_numeric, (s.flags & 1) ? SPLIT_ISOLATED : SPLIT_CONTIGUOUS);
}
} /* namespace */
@@ -354,7 +394,9 @@ bool structural(const std::string& pattern) { return pattern_is_structural(patte
namespace {
int run_pre(const Vocab& v, const std::string& text, std::vector<std::string>& words) {
/* `at_start`: the text is the first fragment, which HuggingFace's Metaspace "first" prepends to. */
int run_pre(const Vocab& v, const std::string& text, std::vector<std::string>& words,
bool at_start) {
std::string t = text;
for (const VocabStep& s : v.steps()) if (step_is_norm(s.kind)) apply_norm(t, s);
@@ -364,13 +406,12 @@ int run_pre(const Vocab& v, const std::string& text, std::vector<std::string>& w
switch (s.kind) {
case RAD_PRE_SPLIT: apply_split(words, s); break;
case RAD_PRE_BYTELEVEL: apply_bytelevel(words, s); break;
case RAD_PRE_METASPACE: apply_metaspace(words, s); break;
case RAD_PRE_WHITESPACE: apply_whitespace(words); break;
case RAD_PRE_METASPACE: apply_metaspace(words, s, at_start); break;
case RAD_PRE_WHITESPACE: apply_whitespace(words, s); break;
case RAD_PRE_PUNCTUATION: apply_punctuation(words, s); break;
case RAD_PRE_DIGITS: apply_digits(words, s); break;
case RAD_PRE_BYTE_FALLBACK:
/* A declaration about what the MODEL does with an unknown piece, not a split.
* The fallback itself lives in bpe() below, where the miss happens. */
/* Declares how unknown pieces are handled, not a split; bpe() applies it. */
break;
default:
RAD_ERR("tokenizer: pre-tokeniser step %u is not implemented", s.kind);
@@ -380,11 +421,17 @@ int run_pre(const Vocab& v, const std::string& text, std::vector<std::string>& w
return RAD_OK;
}
/* The BPE merge loop, in shape from llama.cpp's llm_tokenizer_bpe_session (MIT, 06938ac12).
* A priority queue of candidate bigrams ordered by merge rank; pop the best, splice the two
* symbols into one, and offer the two new neighbours. Stale entries are recognised by comparing
* the recorded text against the symbols' current text rather than by deleting from the queue,
* because deletion from a heap is the expensive operation and staleness is cheap to detect. */
/* The byte-fallback token for byte c, spelt "<0xNN>"; -1 when the vocab has none. */
int32_t byte_token(const Vocab& v, unsigned char c) {
static const char* hex = "0123456789ABCDEF";
const char buf[7] = { '<', '0', 'x', hex[c >> 4], hex[c & 15], '>', 0 };
return v.find(buf);
}
/* The BPE merge loop, after llama.cpp's llm_tokenizer_bpe_session (MIT, 06938ac12). A priority
* queue of candidate bigrams ordered by merge rank: pop the best, splice the two symbols, offer the
* new neighbours. Stale entries are detected by comparing recorded text with the symbols' current
* text instead of deleting from the heap. */
void bpe(const Vocab& v, const std::vector<std::string>& words, std::vector<int32_t>& out) {
struct Symbol { int prev, next; const char* text; size_t n; };
struct Bigram {
@@ -392,8 +439,8 @@ void bpe(const Vocab& v, const std::vector<std::string>& words, std::vector<int3
size_t size;
std::string text;
bool operator<(const Bigram& o) const {
/* Lower rank wins, so the comparator is inverted for a max-heap; ties break on the
* LEFTMOST position, which is what makes the result independent of heap order. */
/* Lower rank wins (inverted for a max-heap); ties go to the leftmost position, so the
* result does not depend on heap order. */
return rank > o.rank || (rank == o.rank && left > o.left);
}
};
@@ -402,9 +449,8 @@ void bpe(const Vocab& v, const std::vector<std::string>& words, std::vector<int3
std::priority_queue<Bigram> work;
int final_prev = -1;
/* Byte fallback is only reachable when the chain declares it; without it an unmatched piece
* is dropped, which is llama.cpp's behaviour and is what a vocab with a full byte alphabet
* relies on (there, nothing is unmatched). */
/* Byte fallback applies only when the chain declares it; otherwise an unmatched piece is
* dropped, as in llama.cpp (a vocab with a full byte alphabet never misses). */
bool have_byte_fallback = false;
bool have_bytelevel = false;
for (const VocabStep& s : v.steps()) {
@@ -419,14 +465,10 @@ void bpe(const Vocab& v, const std::vector<std::string>& words, std::vector<int3
size_t offset = 0;
int index = 0;
/* A user-defined token is taken whole rather than re-split. Added tokens are exact
* strings the vocabulary promises to round-trip; decomposing one into codepoints and
* merging back can land on a different sequence, because the merge table was never
* fitted over them.
*
* ORDINARY VOCABULARY ENTRIES GO THROUGH THE MERGE LOOP unless the vocabulary sets
* `ignore_merges`, which takes any non-control entry whole (core/text/tokenizer.cpp,
* bpe_word, says why control entries are excluded). */
/* A user-defined token is taken whole: added tokens must round-trip, and the merge table
* was not fitted over them. Ordinary entries go through the merge loop unless the vocab
* sets `ignore_merges`, which takes any non-control entry whole (see bpe_word in
* core/text/tokenizer.cpp for why control entries are excluded). */
const int32_t whole = v.find(word);
if (whole >= 0 && (v.type(whole) == RAD_TT_USER_DEFINED ||
(v.build().ignore_merges && v.type(whole) != RAD_TT_CONTROL))) {
@@ -488,9 +530,8 @@ void bpe(const Vocab& v, const std::vector<std::string>& words, std::vector<int3
const int32_t id = v.find(str);
if (id >= 0) { out.push_back(id); continue; }
/* Miss. Decompose into single-byte tokens; how a byte is SPELT depends on the chain.
* Under ByteLevel every byte is already its own mapped codepoint, so the piece splits at
* codepoint boundaries; under byte fallback it is "<0xNN>". */
/* Miss: decompose into single-byte tokens. Under ByteLevel each byte is already a mapped
* codepoint, so split at codepoint boundaries; under byte fallback a byte is "<0xNN>". */
if (have_bytelevel) {
for (size_t k = 0; k < str.size(); ) {
const size_t n = std::min(unicode_len_utf8(str[k]), str.size() - k);
@@ -501,10 +542,8 @@ void bpe(const Vocab& v, const std::vector<std::string>& words, std::vector<int3
k += n;
}
} else if (have_byte_fallback) {
static const char* hex = "0123456789ABCDEF";
for (unsigned char c : str) {
const char buf[7] = { '<', '0', 'x', hex[c >> 4], hex[c & 15], '>', 0 };
const int32_t b = v.find(buf);
const int32_t b = byte_token(v, c);
if (b >= 0) out.push_back(b);
else if (v.unk() >= 0) out.push_back(v.unk());
}
@@ -517,9 +556,8 @@ void bpe(const Vocab& v, const std::vector<std::string>& words, std::vector<int3
}
}
/* Unigram, by Viterbi over a prefix trie -- SentencePiece's algorithm, in shape from
* llama.cpp's llm_tokenizer_ugm_session. Scores are summed in double precision because the
* reference implementation does and the argmax genuinely differs in float on long inputs. */
/* Unigram by Viterbi (SentencePiece's algorithm), after llama.cpp's llm_tokenizer_ugm_session.
* Scores are summed in double, as the reference does; in float the argmax differs on long inputs. */
void unigram(const Vocab& v, const std::string& text, std::vector<int32_t>& out) {
if (text.empty()) return;
const size_t n = text.size();
@@ -528,20 +566,21 @@ void unigram(const Vocab& v, const std::string& text, std::vector<int32_t>& out)
std::vector<Best> best(n + 1, { v.unk(), 0, -DBL_MAX });
best[0] = { v.unk(), 0, 0.0 };
/* The unknown-token penalty: SentencePiece uses (min score - 10). Recomputing it here rather
* than storing it keeps the .rad from carrying a derived number that could disagree. */
/* Unknown-token penalty, as in SentencePiece: min score - 10. Derived here, not stored. */
double unk_penalty = 0.0;
if (!v.build().scores.empty()) {
unk_penalty = *std::min_element(v.build().scores.begin(), v.build().scores.end()) - 10.0;
}
/* Prefix scan by substring lookup, bounded by the longest entry so it stays linear in the
* text. A trie would be faster on a large vocab. */
size_t longest = 0;
for (const std::string& t : v.build().tokens) longest = std::max(longest, t.size());
for (size_t i = 0; i < n; ) {
const size_t cp_len = std::min(unicode_len_utf8(text[i]), n - i);
bool matched_whole_cp = false;
/* Longest-prefix scan. A trie would beat this on a large vocab; the substring lookup is
* O(len) with a bounded len because no vocab entry is longer than the longest token, and
* that bound is what keeps it linear. */
const size_t max_len = std::min(n - i, (size_t)256);
const size_t max_len = std::min(n - i, longest);
for (size_t l = 1; l <= max_len; ++l) {
const int32_t id = v.find(std::string_view(text.data() + i, l));
if (id < 0) continue;
@@ -557,11 +596,9 @@ void unigram(const Vocab& v, const std::string& text, std::vector<int32_t>& out)
i += cp_len;
}
/* A VOCABULARY WITH NO UNK TOKEN HAS NO ID FOR TEXT NO PIECE COVERS, and the Viterbi above
* still routes such text through the unk transition -- whose id is then -1, which is not a
* token and must never reach the output. The span is spelled as byte tokens when the chain
* declares byte fallback and dropped otherwise, as bpe() does with a piece it cannot match.
* Built back to front like the rest of the backtrack, so the bytes go in reversed. */
/* Without an unk token, uncovered text still takes the unk transition with id -1, which must
* never reach the output. Such spans become byte tokens under byte fallback and are dropped
* otherwise, as in bpe(). The backtrack runs back to front, so bytes are pushed reversed. */
const int32_t unk = v.unk();
bool byte_fallback = false;
if (unk < 0)
@@ -575,11 +612,8 @@ void unigram(const Vocab& v, const std::string& text, std::vector<int32_t>& out)
const Best& b = best[pos];
const bool is_unk = (b.id == unk);
if (is_unk && unk < 0) {
static const char* hex = "0123456789ABCDEF";
for (size_t k = pos; k-- > b.from; ) {
const unsigned char c = (unsigned char)text[k];
const char buf[7] = { '<', '0', 'x', hex[c >> 4], hex[c & 15], '>', 0 };
const int32_t id = byte_fallback ? v.find(buf) : -1;
const int32_t id = byte_fallback ? byte_token(v, (unsigned char)text[k]) : -1;
if (id >= 0) out.push_back(id);
else ++dropped;
}
@@ -597,14 +631,15 @@ void unigram(const Vocab& v, const std::string& text, std::vector<int32_t>& out)
byte_fallback ? "lacks a byte token for them" : "declares no byte fallback");
}
/* WordPiece: greedy longest-match-first with a continuation prefix. Kept because BERT-family
* embedding models are a real deployment and they are all WordPiece; it is 30 lines. */
/* WordPiece (BERT-family models): greedy longest-match-first with a "##" continuation prefix; a
* word of more than 100 characters is one unknown token, as in HuggingFace. */
void wordpiece(const Vocab& v, const std::vector<std::string>& words, std::vector<int32_t>& out) {
for (const std::string& w : words) {
if (w.empty()) continue;
size_t i = 0;
std::vector<int32_t> piece;
bool ok = true;
bool ok = unicode_cpts_from_utf8(w).size() <= 100;
if (!ok) i = w.size();
while (i < w.size()) {
size_t j = w.size();
int32_t id = -1;
@@ -631,13 +666,10 @@ int encode(const Vocab& v, std::string_view text, std::vector<int32_t>& out,
if (add_special && v.add_bos() && v.bos() >= 0) out.push_back(v.bos());
/* Special-token partitioning. The text is cut into (raw, token, raw, token, ...) around any
* declared special token that appears literally, before any other step touches it, because a
* special token is not something the pre-tokeniser is allowed to split.
*
* `parse_special == false` means a control token typed by a user is ordinary text. That is
* not a nicety: without it, user content containing "<|im_start|>system" reaches the model
* as an actual role switch. */
/* Cut the text into (raw, token, raw, ...) around literal special tokens before any other
* step, so the pre-tokeniser never splits one. With `parse_special == false` a control token
* in user text is ordinary text; otherwise "<|im_start|>system" in user content would be a
* real role switch. */
struct Frag { bool is_token; int32_t id; size_t off, len; };
std::vector<Frag> frags;
const std::string raw(text);
@@ -673,14 +705,14 @@ int encode(const Vocab& v, std::string_view text, std::vector<int32_t>& out,
const std::string chunk = raw.substr(f.off, f.len);
std::vector<std::string> words;
RAD_TRY(run_pre(v, chunk, words));
RAD_TRY(run_pre(v, chunk, words, f.off == 0));
switch (v.kind()) {
case RAD_TOK_BPE: bpe(v, words, out); break;
case RAD_TOK_WORDPIECE: wordpiece(v, words, out); break;
case RAD_TOK_UNIGRAM: {
/* Unigram runs Viterbi over the whole normalised fragment; the pre-tokeniser's
* job there is only to insert the metaspace, so the words are rejoined. */
/* Unigram runs over the whole fragment; pre-tokenisation only inserted the
* metaspace, so rejoin the words. */
std::string joined;
for (const std::string& w : words) joined += w;
unigram(v, joined, out);
+7 -8
View File
@@ -1,15 +1,12 @@
/* tokref.h -- a reference encoder for checking core/text's.
/* tokref.h -- an independent reference encoder for checking core/text's.
*
* `encode` runs the declared chain the way llama.cpp does: its structural splitters for the
* patterns it recognises, std::regex over a category-collapsed copy of the text for the rest, and
* a string-keyed bigram queue for the merge. It shares no code with core/text/tokenizer_regex.cpp
* or tokenizer_bpe.cpp, which is the point: tokenizer_test and rad-tokcheck hold core/text's
* encoder to it id for id.
* or tokenizer_bpe.cpp; tokenizer_test and rad-tokcheck compare the two id for id.
*
* WHERE IT IS KNOWN TO DIFFER FROM HUGGINGFACE TOKENIZERS, which is the reference both are
* ultimately judged by. core/text's encoder follows HuggingFace in each case, so these are the only
* places the two encoders may disagree, and the tests that compare them name the case rather
* than avoiding the input:
* Known differences from HuggingFace tokenizers, which core/text follows. These are the only
* places the two encoders may disagree, and the comparing tests name each case:
* - `(?i:'s|'t|'re|'ve|'m|'ll|'d)` is rewritten to `'[sS]|...` before matching, which drops
* Oniguruma's case orbit of 's': U+017F LATIN SMALL LETTER LONG S. "'ſ" is a contraction to
* HuggingFace and not here.
@@ -20,7 +17,9 @@
* upper/lower-case letter classes and uses its own Han ranges.
* - `\d{1,3}(?=(?:\d{3})*\b)` is split by llama.cpp's AFMoE digit rule, which also splits digit
* runs followed by letters; the pattern does not.
* - Split behaviours other than Isolated are applied as Isolated.
* - Split behaviours other than Isolated are applied as Isolated. (Punctuation and Digits
* apply theirs: they are written here from HuggingFace's character predicates, over the
* category and \s tables of core/text/tokenizer_ucd.h, rather than as patterns.)
* - A regex Replace normaliser runs std::regex (ECMAScript, bytes) and expands `$` in its
* replacement; HuggingFace inserts the replacement verbatim.
*/
+24 -17
View File
@@ -1,17 +1,15 @@
/* vmemprobe -- what a virtual-memory decommit actually returns to the card.
/* vmemprobe -- measures what a virtual-memory decommit actually returns to the card.
*
* The elastic KV pool rests on one claim about the driver: that unmapping a sub-range of a live
* reservation gives the card back memory another pool can then commit. That is not something the
* pool can check for itself -- a commit that fails looks the same as a pool that is simply full --
* and it is not something the API promises. This measures it.
* The elastic KV pool assumes that unmapping a sub-range of a live reservation frees memory another
* pool can commit. The API does not promise this and the pool cannot detect it (a failed commit
* looks like a full pool).
*
* Each trial commits a range, lets go of it a different way, and reports the card free counter
* beside what a real hipMalloc can still reach, because the two disagree exactly where the driver
* has stopped crediting something back.
* Each trial commits a range, releases it a different way, and reports the card's free counter
* beside what hipMalloc can still reach; they disagree where the driver failed to credit memory
* back.
*
* Build: hipcc -O1 --offload-arch=<gfx> -I/opt/rocm/include -L/opt/rocm/lib -o vmemprobe vmemprobe.cpp
* Run it on an IDLE card: every number here is a free-memory reading and another process
* allocating beside it makes all of them lies. */
* Run on an idle card: other allocations skew every reading. */
#include <hip/hip_runtime.h>
#include <cstdio>
#include <cstdlib>
@@ -35,8 +33,18 @@ static void trial(const char* what, bool keep_handle, bool piecewise, bool free_
if (hipMemAddressReserve(&base, bytes, G, nullptr, 0) != hipSuccess) { printf("%-34s reserve failed\n", what); return; }
const double f0 = freem();
hipMemGenericAllocationHandle_t h{};
if (hipMemCreate(&h, bytes, &prop, 0) != hipSuccess) { printf("%-34s create failed\n", what); return; }
if (hipMemMap(base, bytes, 0, h, 0) != hipSuccess) { printf("%-34s map failed\n", what); return; }
/* A failed trial gives back what it took, or later trials read less free memory. */
if (hipMemCreate(&h, bytes, &prop, 0) != hipSuccess) {
printf("%-34s create failed\n", what);
(void)hipMemAddressFree(base, bytes);
return;
}
if (hipMemMap(base, bytes, 0, h, 0) != hipSuccess) {
printf("%-34s map failed\n", what);
(void)hipMemRelease(h);
(void)hipMemAddressFree(base, bytes);
return;
}
if (!keep_handle) (void)hipMemRelease(h);
(void)hipMemSetAccess(base, bytes, &desc, 1);
const double f1 = freem();
@@ -54,9 +62,8 @@ static void trial(const char* what, bool keep_handle, bool piecewise, bool free_
what, f0, f1, f2, f3, reach(24));
if (!free_va) (void)hipMemAddressFree(base, bytes);
}
/* THE CYCLE AN ELASTIC POOL ACTUALLY PERFORMS: commit a sub-range of a long-lived reservation,
* unmap it, commit it again. A pool that grows and shrinks with load does this all run, so a
* card that fell on every pass would be one the engine leaks away under a varying workload. */
/* The elastic pool's cycle: commit a sub-range of a long-lived reservation, unmap it, repeat. Free
* memory that drops on every pass would leak under a varying workload. */
static void cycle(int n) {
const size_t total = (8ull << 30) / G * G;
const size_t part = (2ull << 30) / G * G;
@@ -66,8 +73,8 @@ static void cycle(int n) {
total / 1073741824.0, part / 1073741824.0);
for (int i = 0; i < n; ++i) {
hipMemGenericAllocationHandle_t h{};
if (hipMemCreate(&h, part, &prop, 0) != hipSuccess) { printf(" pass %d: create FAILED\n", i); break; }
if (hipMemMap(base, part, 0, h, 0) != hipSuccess) { (void)hipMemRelease(h); printf(" pass %d: map FAILED\n", i); break; }
if (hipMemCreate(&h, part, &prop, 0) != hipSuccess) { printf(" pass %d: create failed\n", i); break; }
if (hipMemMap(base, part, 0, h, 0) != hipSuccess) { (void)hipMemRelease(h); printf(" pass %d: map failed\n", i); break; }
(void)hipMemRelease(h);
(void)hipMemSetAccess(base, part, &desc, 1);
const double fm = freem();