radiance 1.0.0

This commit is contained in:
Deadcode committed 2026-10-04 12:02:41 +02:00
commit ae74a8aebf
616 files changed
+338692

No files matched your search

+105
View File
@@ -0,0 +1,105 @@
# 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.
#
# 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.
set(RAD_TOOL_SHARED
${CMAKE_CURRENT_SOURCE_DIR}/iface.cpp
${CMAKE_CURRENT_SOURCE_DIR}/opshapes.cpp
${CMAKE_CURRENT_SOURCE_DIR}/kfixture.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.
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.
#
# 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.
set_target_properties(${name} PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
ENABLE_EXPORTS ON)
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.
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)
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.
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.
find_package(OpenMP QUIET)
if(OpenMP_CXX_FOUND)
target_link_libraries(rad-convert PRIVATE OpenMP::OpenMP_CXX)
endif()
rad_add_tool(rad-kbench rad_kbench.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)
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)
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.
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.
if(RAD_BUILD_TESTS)
add_executable(rad-chatparse rad_chatparse.cpp)
target_link_libraries(rad-chatparse PRIVATE rad_legacy_toolparse)
target_include_directories(rad-chatparse PRIVATE ${CMAKE_SOURCE_DIR}/core ${CMAKE_SOURCE_DIR}/abi)
set_target_properties(rad-chatparse PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
endif()
+204
View File
@@ -0,0 +1,204 @@
/* 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.
*
* 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.
*
* 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.
*
* 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.
*
* 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.
*/
const fs = require('fs');
const html = fs.readFileSync(process.argv[2], 'utf8');
const payloads = JSON.parse(fs.readFileSync(process.argv[3], 'utf8'));
const i0 = html.lastIndexOf('<script>');
const i1 = html.lastIndexOf('</script>');
if (i0 < 0 || i1 < 0) { console.log('NO SCRIPT'); process.exit(2); }
let js = html.slice(i0 + 8, i1);
const writes = [];
const mkEl = (id) => {
const el = {
id, _text: '', hidden: false, className: '', innerHTML: '', value: '',
style: new Proxy({}, { get: () => '', set: () => true }),
dataset: {}, children: [], scrollTop: 0, scrollHeight: 0, offsetWidth: 100, offsetHeight: 20,
clientWidth: 800, clientHeight: 400, width: 0, height: 0,
getContext: () => ({ createImageData: (w, h) => ({ data: new Uint8ClampedArray(w * h * 4), width: w, height: h }),
putImageData(){}, clearRect(){}, fillRect(){}, drawImage(){},
beginPath(){}, moveTo(){}, lineTo(){}, stroke(){}, fill(){},
save(){}, restore(){}, translate(){}, scale(){}, setTransform(){},
fillText(){}, measureText: () => ({ width: 10 }) }),
classList: { add(){}, remove(){}, toggle(){}, contains(){ return false; } },
appendChild(c){ this.children.push(c); return c; },
removeChild(){}, remove(){}, insertBefore(c){ this.children.push(c); return c; },
setAttribute(){}, getAttribute(){ return null; }, removeAttribute(){},
addEventListener(){}, querySelector(){ return mkEl('q'); },
querySelectorAll(){ return []; }, getBoundingClientRect(){ return {width:100,height:20,top:0,left:0}; },
closest(){ return null; }, focus(){}, blur(){}, click(){},
};
el.parentNode = {
style: new Proxy({}, { get: () => '', set: () => true }),
classList: { add(){}, remove(){}, toggle(){}, contains(){ return false; } },
querySelector: () => mkEl(id + '>sub'), querySelectorAll: () => [],
appendChild(){}, removeChild(){}, parentNode: null, children: [],
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. */
const tn = { nodeType: 3, _v: '' };
Object.defineProperty(tn, 'nodeValue', {
get(){ return tn._v; },
set(v){ tn._v = String(v); writes.push([id + '#text', String(v)]); },
});
el.firstChild = tn; el.lastChild = tn;
/* The page indexes childNodes past what a stub would hold -- the sparklines address one
* path per series. Draw them on demand rather than guessing how many there are. */
el.childNodes = new Proxy([tn], {
get(t, p) {
if (typeof p === 'string' && /^[0-9]+$/.test(p) && t[p] === undefined) t[p] = mkEl(id + '>child' + p);
return t[p];
},
});
Object.defineProperty(el, 'textContent', {
get(){ return el._text; },
set(v){ el._text = String(v); writes.push([id, String(v)]); },
});
return el;
};
const els = new Map();
const get = (id) => { if (!els.has(id)) els.set(id, mkEl(id)); return els.get(id); };
global.document = {
hidden: false,
getElementById: get,
createElement: (t) => mkEl('<' + t + '>'),
createDocumentFragment: () => mkEl('#frag'),
createTextNode: (t) => { const n = mkEl('#text'); n.textContent = t; return n; },
createElementNS: (ns, t) => mkEl('<' + t + '>'),
querySelector: () => mkEl('q'), querySelectorAll: () => [],
addEventListener(){}, body: mkEl('body'), documentElement: mkEl('html'),
};
global.window = global;
global.location = { hash: '', href: 'http://x/', pathname: '/' };
global.performance = { now: () => Date.now() };
global.requestAnimationFrame = (f) => f();
global.setInterval = () => 0;
global.setTimeout = (f) => { try { f(); } catch (e) {} return 0; };
global.navigator = { userAgent: 'node', clipboard: { writeText(){} } };
global.getComputedStyle = () => new Proxy({}, { get: () => '' });
global.EventSource = function(){ this.addEventListener = () => {}; this.close = () => {}; };
global.matchMedia = () => ({ matches: false, addEventListener(){}, addListener(){} });
let call = 0;
global.fetch = async (u) => ({
ok: true, status: 200,
json: async () => {
if (String(u).indexOf('stats') >= 0) return payloads[Math.min(call++, payloads.length - 1)];
return {};
},
text: async () => '',
});
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. */
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;";
js += "\n;globalThis.__fmt = typeof ladder === 'function' ? { hb, hbOf, rate, cnt, cnt3, num3, " +
"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. */
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'],
['hb', [G - 1], '1.00 GiB'], ['hb', [10.5 * G], '10.5 GiB'], ['hb', [65.2 * T], '65.2 TiB'],
['hb', [null], '–'],
['hbOf', [2.12 * G, 4.33 * G, ' / '], '2.12 / 4.33 GiB'],
['hbOf', [960 * 2 ** 20, 1.2 * G, ' / '], '960 MiB / 1.20 GiB'],
['rate', [0], '0 B/s'], ['rate', [999.4], '999 B/s'], ['rate', [999.5], '1.00 kB/s'],
['rate', [3.531e9], '3.53 GB/s'], ['rate', [999.96e6], '1.00 GB/s'],
['cnt3', [999], '999'], ['cnt3', [1000], '1.00k'], ['cnt3', [9995], '10.0k'],
['cnt3', [999950], '1.00M'], ['cnt3', [65694228], '65.7M'],
['num3', [0], '0'], ['num3', [0.05309], '0.05'], ['num3', [9.996], '10.0'], ['num3', [99.96], '100'],
['num3', [111.177288068], '111'], ['num3', [1234.5], '1.23k'],
['cnt', [1234], '1234'], ['cnt', [12345], '12' + NB + '345'], ['cnt', [1967390], '1' + NB + '967' + NB + '390'],
['cnt', [null], '–'],
['pct', [0], '0.0%'], ['pct', [0.0004], '<0.1%'], ['pct', [0.5], '50.0%'], ['pct', [0.9984], '99.8%'],
['pct', [0.99996], '>99.9%'], ['pct', [1], '100.0%'], ['pct', [0.004, 0], '<1%'], ['pct', [0.9984, 0], '>99%'],
['pctn', [0.4958, 0], '50'],
['dur', [0], '0 ms'], ['dur', [0.5201], '520 ms'], ['dur', [0.9996], '1.00 s'], ['dur', [9.996], '10.0 s'],
['dur', [59.96], '1m 00s'], ['dur', [173], '2m 53s'], ['dur', [3599.6], '1h 00m'],
['dur', [52274], '14h 31m'], ['dur', [86399], '1d 00h'], ['dur', [200000], '2d 08h'],
];
let fmtBad = 0;
if (!globalThis.__fmt) {
console.log(' no formatter block in this page; boundary cases skipped');
} else {
for (const [f, args, want] of CASES) {
const got = globalThis.__fmt[f](...args);
if (got !== want) { fmtBad++; console.log(' FORMAT ' + f + '(' + args.join(', ') + ') = "' + got + '", want "' + want + '"'); }
}
for (const [ms, n, u] of [[34.56, '34.56', 'ms'], [99.996, '100.0', 'ms'], [999.96, '1.00', 's']]) {
const got = globalThis.__fmt.stepTime(ms);
if (got.n !== n || got.u !== u) { fmtBad++; console.log(' FORMAT stepTime(' + ms + ') = ' + JSON.stringify(got)); }
}
console.log(' ' + (CASES.length + 3 - fmtBad) + ' of ' + (CASES.length + 3) + ' formatter boundary cases hold');
}
(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. */
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. */
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)');
if (globalThis.__err) console.log(' update() threw: ' +
(globalThis.__err.stack ? globalThis.__err.stack.split('\n').slice(0,4).join('\n ') : globalThis.__err));
if (threw) { console.log('THREW: ' + (threw && threw.stack ? threw.stack.split('\n').slice(0,3).join(' | ') : threw)); }
const bad = writes.filter(([, v]) => /NaN|undefined|Infinity|\[object Object\]|null/.test(v));
/* A raw float; four digits in front of a unit or a prefix; a locale's thousands separator. */
const shape = writes.filter(([, v]) =>
/\d\.\d{4,}/.test(v) ||
/\d{4,}(\.\d+)?\s?(k|M|G|T|B|KiB|MiB|GiB|TiB|kB\/s|MB\/s|GB\/s|ms)(?![A-Za-z])/.test(v) ||
/\d,\d{3}(?!\d)/.test(v));
if (shape.length) {
console.log(' BADLY FORMATTED (' + shape.length + '):');
const seen = new Set();
for (const [id, v] of shape) { const k = id + '=' + v; if (!seen.has(k)) { seen.add(k); console.log(' #' + id + ' -> "' + v + '"'); } }
}
console.log(' ' + writes.length + ' text writes across ' + payloads.length + ' polls');
if (bad.length) {
console.log(' BAD VALUES (' + bad.length + '):');
const seen = new Set();
for (const [id, v] of bad) { const k = id + '=' + v; if (!seen.has(k)) { seen.add(k); console.log(' #' + id + ' -> "' + v + '"'); } }
} else {
console.log(' no NaN / undefined / Infinity written');
}
process.exit(threw || bad.length || shape.length || fmtBad ? 1 : 0);
})();
+244
View File
@@ -0,0 +1,244 @@
/* 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.
*
* Not built by CMake, because it links the system Oniguruma and nothing else in the tree does:
*
* 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.
*/
#include <oniguruma.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <numeric>
#include <set>
#include <string>
#include <vector>
namespace {
constexpr uint32_t kMax = 0x110000;
bool is_surrogate(uint32_t c) { return c >= 0xD800 && c <= 0xDFFF; }
std::string utf8(uint32_t c) {
std::string s;
if (c < 0x80) {
s += (char)c;
} else if (c < 0x800) {
s += (char)(0xC0 | (c >> 6));
s += (char)(0x80 | (c & 0x3F));
} else if (c < 0x10000) {
s += (char)(0xE0 | (c >> 12));
s += (char)(0x80 | ((c >> 6) & 0x3F));
s += (char)(0x80 | (c & 0x3F));
} else {
s += (char)(0xF0 | (c >> 18));
s += (char)(0x80 | ((c >> 12) & 0x3F));
s += (char)(0x80 | ((c >> 6) & 0x3F));
s += (char)(0x80 | (c & 0x3F));
}
return s;
}
struct Re {
regex_t* reg = nullptr;
OnigRegion* region = nullptr;
explicit Re(const std::string& pat) {
OnigErrorInfo einfo;
const OnigUChar* p = (const OnigUChar*)pat.data();
const int r = onig_new(&reg, p, p + pat.size(), ONIG_OPTION_NONE, ONIG_ENCODING_UTF8,
ONIG_SYNTAX_RUBY, &einfo);
if (r != ONIG_NORMAL) {
std::fprintf(stderr, "onig_new(%s) failed: %d\n", pat.c_str(), r);
std::exit(1);
}
region = onig_region_new();
}
~Re() { onig_region_free(region, 1); onig_free(reg); }
bool matches_whole(uint32_t c) const {
const std::string s = utf8(c);
const OnigUChar* b = (const OnigUChar*)s.data();
const OnigUChar* e = b + s.size();
return onig_match(reg, b, e, b, region, ONIG_OPTION_NONE) == (int)s.size();
}
};
using Ranges = std::vector<std::pair<uint32_t, uint32_t>>;
Ranges ranges_of(const std::string& pat) {
Re re(pat);
Ranges out;
for (uint32_t c = 0; c < kMax; ++c) {
if (is_surrogate(c) || !re.matches_whole(c)) continue;
if (!out.empty() && out.back().second + 1 == c) out.back().second = c;
else out.push_back({ c, c });
}
return out;
}
void emit_ranges(const char* name, const Ranges& r) {
std::printf("const CpRange %s[] = {\n", name);
for (size_t i = 0; i < r.size(); ++i)
std::printf("%s{0x%X,0x%X},%s", i % 6 == 0 ? " " : "", r[i].first, r[i].second,
i % 6 == 5 || i + 1 == r.size() ? "\n" : " ");
std::printf("};\nconst size_t %s_n = sizeof(%s) / sizeof(%s[0]);\n\n", name, name, name);
}
} /* namespace */
int main() {
OnigEncoding encs[] = { ONIG_ENCODING_UTF8 };
onig_initialize(encs, 1);
/* The 29 general categories Oniguruma can name, in the order of rad::ucd::Gc. Cs has no
* member Oniguruma can be asked about (a surrogate is not UTF-8), so it is assigned below. */
static const char* kGc[] = {
"Lu", "Ll", "Lt", "Lm", "Lo", "Mn", "Mc", "Me", "Nd", "Nl", "No",
"Pc", "Pd", "Ps", "Pe", "Pi", "Pf", "Po", "Sm", "Sc", "Sk", "So",
"Zs", "Zl", "Zp", "Cc", "Cf", "Cs", "Co", "Cn",
};
const int kCs = 27;
std::vector<uint8_t> gc(kMax, 0xFF);
for (int g = 0; g < 30; ++g) {
if (g == kCs) continue;
Re re(std::string("\\p{") + kGc[g] + "}");
for (uint32_t c = 0; c < kMax; ++c) {
if (is_surrogate(c) || !re.matches_whole(c)) continue;
if (gc[c] != 0xFF) {
std::fprintf(stderr, "U+%04X is in two categories\n", c);
return 1;
}
gc[c] = (uint8_t)g;
}
}
for (uint32_t c = 0xD800; c <= 0xDFFF; ++c) gc[c] = kCs;
for (uint32_t c = 0; c < kMax; ++c) {
if (gc[c] == 0xFF) {
std::fprintf(stderr, "U+%04X is in no category\n", c);
return 1;
}
}
std::printf(
"/* tokenizer_ucd.cpp -- GENERATED by tools/gen_tokenizer_ucd.cpp; do not edit.\n"
" *\n"
" * Oniguruma %d.%d.%d, which is what HuggingFace tokenizers matches pre-tokeniser patterns\n"
" * with. See the generator for why the tables are read out of it. */\n"
"#include \"text/tokenizer_ucd.h\"\n\nnamespace rad {\nnamespace ucd {\n\n",
ONIGURUMA_VERSION_MAJOR, ONIGURUMA_VERSION_MINOR, ONIGURUMA_VERSION_TEENY);
/* General category as runs: each entry starts a run that lasts until the next one. */
std::printf("const GcRun k_gc_runs[] = {\n");
size_t n = 0;
for (uint32_t c = 0; c < kMax; ++c) {
if (c > 0 && gc[c] == gc[c - 1]) continue;
std::printf("%s{0x%X,%u},%s", n % 6 == 0 ? " " : "", c, gc[c], n % 6 == 5 ? "\n" : " ");
++n;
}
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. */
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);
return 1;
}
}
emit_ranges("k_white_space", ranges_of("\\s"));
emit_ranges("k_digit", ranges_of("\\d"));
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. */
static const char* kScripts[] = {
"Han", "Hiragana", "Katakana", "Hangul", "Bopomofo", "Latin", "Greek", "Cyrillic",
"Armenian", "Hebrew", "Arabic", "Thai", "Lao", "Khmer", "Myanmar", "Tibetan",
"Devanagari", "Bengali", "Gurmukhi", "Gujarati", "Oriya", "Tamil", "Telugu", "Kannada",
"Malayalam", "Sinhala", "Georgian", "Ethiopic", "Mongolian", "Common", "Inherited",
};
std::vector<std::string> script_tables;
for (const char* s : kScripts) {
std::string name = std::string("k_script_") + s;
emit_ranges(name.c_str(), ranges_of(std::string("\\p{") + s + "}"));
script_tables.push_back(name);
}
std::printf("const ScriptTable k_scripts[] = {\n");
for (size_t i = 0; i < script_tables.size(); ++i)
std::printf(" { \"%s\", %s, %s_n },\n", kScripts[i], script_tables[i].c_str(),
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. */
std::vector<uint32_t> parent(kMax);
std::iota(parent.begin(), parent.end(), 0u);
auto find = [&](uint32_t x) {
while (parent[x] != x) x = parent[x] = parent[parent[x]];
return x;
};
std::set<uint32_t> multi;
for (uint32_t c = 0; c < kMax; ++c) {
if (is_surrogate(c)) continue;
const std::string s = utf8(c);
OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM];
const OnigUChar* b = (const OnigUChar*)s.data();
const int k = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(ONIG_ENCODING_UTF8, ONIGENC_CASE_FOLD_DEFAULT,
b, b + s.size(), items);
for (int i = 0; i < k; ++i) {
if (items[i].byte_len != (int)s.size()) continue;
if (items[i].code_len != 1) { multi.insert(c); continue; }
const uint32_t a = find(c), d = find(items[i].code[0]);
if (a != d) parent[std::max(a, d)] = std::min(a, d);
}
}
std::map<uint32_t, std::vector<uint32_t>> orbits;
for (uint32_t c = 0; c < kMax; ++c) {
if (is_surrogate(c)) continue;
orbits[find(c)].push_back(c);
}
std::printf("/* Each orbit is its length followed by its members, ascending. */\n");
std::printf("const uint32_t k_case_orbits[] = {\n");
size_t w = 0;
for (const auto& [rep, members] : orbits) {
if (members.size() < 2) continue;
std::printf(" %zu,", members.size());
for (uint32_t m : members) std::printf(" 0x%X,", m);
std::printf("\n");
++w;
}
std::printf("};\nconst size_t k_case_orbits_n = sizeof(k_case_orbits) / sizeof(k_case_orbits[0]);\n\n");
std::printf("const uint32_t k_case_multi[] = {\n");
n = 0;
for (uint32_t c : multi) {
std::printf("%s0x%X,%s", n % 10 == 0 ? " " : "", c, n % 10 == 9 ? "\n" : " ");
++n;
}
std::printf("\n};\nconst size_t k_case_multi_n = sizeof(k_case_multi) / sizeof(k_case_multi[0]);\n\n");
std::printf("} /* namespace ucd */\n} /* namespace rad */\n");
std::fprintf(stderr, "%zu case orbits, %zu multi-codepoint folds\n", w, multi.size());
return 0;
}
+54
View File
@@ -0,0 +1,54 @@
/* 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.
*
* 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.
*/
#include "iface.h"
#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. */
std::string rad_home() {
if (const char* e = std::getenv("RADIANCE_HOME")) if (*e) return e;
#ifdef RAD_DEFAULT_HOME
return RAD_DEFAULT_HOME;
#else
return ".";
#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_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;
}
} /* namespace rad */
+45
View File
@@ -0,0 +1,45 @@
/* 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-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).
*/
#pragma once
#include "rad_core.h"
#include "format/radfile.h"
#include "text/gguf.h"
#include "build/startup.h"
#include <string>
#include <vector>
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. */
/* ================================================================== 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. */
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 */
/* 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);
} /* namespace rad */
+104
View File
@@ -0,0 +1,104 @@
#!/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.
#
# 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: 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.
set -eu
BUILD=${1:-build}
OUT=${2:-analysis.md}
ROOT=$(cd "$(dirname "$0")/.." && pwd)
CC_JSON="$BUILD/compile_commands.json"
TIDY=$(command -v clang-tidy || echo /opt/rocm/llvm/bin/clang-tidy)
{
echo "## Static and dynamic analysis"
echo
echo "Advisory, and generated separately from the measurements above:"
echo "\`tools/kbench-analysis.sh\` runs on a machine that need not have a GPU."
echo
} > "$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'
if [ ! -f "$CC_JSON" ]; then
echo "clang-tidy: skipped, no $CC_JSON (configure with -DCMAKE_EXPORT_COMPILE_COMMANDS=ON)" >> "$OUT"
echo >> "$OUT"
elif [ ! -x "$TIDY" ] && ! command -v clang-tidy > /dev/null 2>&1; then
echo "clang-tidy: not installed on this machine" >> "$OUT"
echo >> "$OUT"
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"
N=$(grep -c "warning:" "$TMP" || true)
echo "### clang-tidy" >> "$OUT"
echo >> "$OUT"
echo "\`bugprone-*\`, \`clang-analyzer-*\` and \`performance-*\` over every host translation unit" >> "$OUT"
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"
if [ "$N" -gt 0 ]; then
echo >> "$OUT"
echo "| check | count |" >> "$OUT"
echo "|---|---|" >> "$OUT"
grep -o '\[[a-z][a-z-]*-[a-z][a-z.-]*\]$' "$TMP" | sort | uniq -c | sort -rn |
while read -r n c; do echo "| \`${c}\` | $n |" >> "$OUT"; done
fi
echo >> "$OUT"
rm -f "$TMP"
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.
echo "### AddressSanitizer + UndefinedBehaviorSanitizer" >> "$OUT"
echo >> "$OUT"
SAN="$BUILD-asan"
if [ -x "$SAN/bin/rad-kbench" ]; then
LOG=$(mktemp)
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
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 "**Memory safety** section for why the device side cannot be sanitised on this card." >> "$OUT"
echo >> "$OUT"
echo "- $E report(s)" >> "$OUT"
if [ "$E" -gt 0 ]; then
echo >> "$OUT"
echo '```' >> "$OUT"
grep -h "ERROR: AddressSanitizer\|runtime error:" "$LOG" | sort | uniq -c | head -40 >> "$OUT"
echo '```' >> "$OUT"
fi
rm -f "$LOG"
else
echo "Not run: no sanitised build at \`$SAN\`. Build one with" >> "$OUT"
echo >> "$OUT"
echo '```sh' >> "$OUT"
echo "cmake -S . -B $SAN -DRAD_ASAN=ON && cmake --build $SAN -j8" >> "$OUT"
echo '```' >> "$OUT"
fi
echo >> "$OUT"
echo "analysis written to $OUT" >&2
+657
View File
@@ -0,0 +1,657 @@
/* kfixture.cpp -- reading and writing the recorded reference. See kfixture.h for why it exists.
*
* 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.
*/
#include "kfixture.h"
#include "opshapes.h"
#include "format/encoding.h"
#include "rad_plugin.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. */
struct W {
FILE* f;
bool ok = true;
void raw(const void* p, size_t n) { if (ok && std::fwrite(p, 1, n, f) != n) ok = false; }
void u8(uint8_t v) { raw(&v, 1); }
void u32(uint32_t v) { raw(&v, 4); }
void i64(int64_t v) { raw(&v, 8); }
void u64(uint64_t v) { raw(&v, 8); }
void f64(double v) { raw(&v, 8); }
void str(const std::string& s) { u32((uint32_t)s.size()); raw(s.data(), s.size()); }
void f32v(const std::vector<float>& v) {
u32((uint32_t)v.size()); raw(v.data(), v.size() * sizeof(float));
}
void i64v(const std::vector<int64_t>& v) {
u32((uint32_t)v.size()); raw(v.data(), v.size() * sizeof(int64_t));
}
};
struct R {
FILE* f;
bool ok = true;
void raw(void* p, size_t n) { if (ok && std::fread(p, 1, n, f) != n) ok = false; }
uint8_t u8() { uint8_t v = 0; raw(&v, 1); return v; }
uint32_t u32() { uint32_t v = 0; raw(&v, 4); return v; }
int64_t i64() { int64_t v = 0; raw(&v, 8); return v; }
uint64_t u64() { uint64_t v = 0; raw(&v, 8); return v; }
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. */
if (!ok || n > (1u << 20)) { ok = false; return {}; }
std::string s(n, '\0');
raw(s.data(), n);
return s;
}
std::vector<float> f32v() {
const uint32_t n = u32();
if (!ok || n > (1u << 24)) { ok = false; return {}; }
std::vector<float> v(n);
raw(v.data(), (size_t)n * sizeof(float));
return v;
}
std::vector<int64_t> i64v() {
const uint32_t n = u32();
if (!ok || n > RAD_MAX_RANK) { ok = false; return {}; }
std::vector<int64_t> v(n);
raw(v.data(), (size_t)n * sizeof(int64_t));
return v;
}
};
} /* namespace */
uint64_t kf_operand_seed(uint64_t case_seed, int k) {
uint64_t x = case_seed ^ (0x9E3779B97F4A7C15ull * (uint64_t)(k + 1));
return rad_splitmix(x);
}
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. */
if (n <= KF_SAMPLES) {
out->reserve((size_t)n);
for (int64_t i = 0; i < n; ++i) out->push_back(i);
return;
}
out->reserve(KF_SAMPLES);
uint64_t s = seed;
for (int i = 0; i < KF_SAMPLES; ++i)
out->push_back((int64_t)(rad_splitmix(s) % (uint64_t)n));
}
int Kfixture::save(const std::string& path) const {
FILE* f = std::fopen(path.c_str(), "wb");
if (!f) return RAD_E_IO;
W w{ f };
w.raw(KF_MAGIC, 4);
w.u32(version);
w.u32((uint32_t)KF_SAMPLES);
w.str(source);
w.str(oracle);
w.str(recorded);
w.u32((uint32_t)cases.size());
for (const KfCase& c : cases) {
w.str(c.op);
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);
w.u32((uint32_t)p.kind);
w.u64((uint64_t)p.i);
w.f64(p.d);
w.str(p.s);
}
w.u32((uint32_t)c.opd.size());
for (const KfOperand& o : c.opd) {
w.u32((uint32_t)o.role);
w.u32(o.dtype);
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.i64(o.idx_max);
w.i64(o.idx_const);
w.i64(o.fill_chunk);
w.u8(o.has_enc ? 1 : 0);
if (o.has_enc) {
w.raw(&o.enc, sizeof o.enc);
w.u32((uint32_t)o.sel.size());
for (size_t k = 0; k < o.sel.size(); ++k) {
w.u32((uint32_t)o.sel[k]);
w.i64(o.sel_rows[k]);
w.i64(o.sel_cols[k]);
}
}
w.u8(o.have_ref ? 1 : 0);
if (o.have_ref) {
w.i64(o.ref_n);
w.f64(o.ref_sumsq);
w.i64(o.ref_nonfinite);
w.f32v(o.sample);
}
}
}
const bool ok = w.ok;
std::fclose(f);
return ok ? RAD_OK : RAD_E_IO;
}
int Kfixture::load(const std::string& path) {
FILE* f = std::fopen(path.c_str(), "rb");
if (!f) return RAD_E_NOTFOUND;
R r{ f };
char magic[4];
r.raw(magic, 4);
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) {
std::fclose(f);
return RAD_E_FORMAT;
}
source = r.str();
oracle = r.str();
recorded = r.str();
const uint32_t n = r.u32();
if (!r.ok || n > (1u << 20)) { std::fclose(f); return RAD_E_FORMAT; }
cases.clear();
cases.reserve(n);
for (uint32_t ci = 0; ci < n && r.ok; ++ci) {
KfCase c;
c.op = r.str();
c.seed = r.u64();
c.m = r.i64();
c.band = r.str();
c.speed_only = r.u8() != 0;
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) {
KfParam p;
p.key = r.str();
p.kind = (int)r.u32();
p.i = (long long)r.u64();
p.d = r.f64();
p.s = r.str();
c.params.push_back(std::move(p));
}
const uint32_t no = r.u32();
if (!r.ok || no > 64) { r.ok = false; break; }
for (uint32_t i = 0; i < no && r.ok; ++i) {
KfOperand o;
o.role = (int)r.u32();
o.dtype = r.u32();
o.shape = r.i64v();
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.idx_max = r.i64();
o.idx_const = r.i64();
o.fill_chunk = r.i64();
o.has_enc = r.u8() != 0;
if (o.has_enc) {
r.raw(&o.enc, sizeof o.enc);
const uint32_t ns = r.u32();
if (!r.ok || ns == 0 || ns > RAD_ENC_MAX_PLANES || !rad_enc_valid(&o.enc)) {
r.ok = false;
break;
}
for (uint32_t k = 0; k < ns; ++k) {
const uint32_t ix = r.u32();
if (ix >= (uint32_t)o.enc.n_planes) r.ok = false;
o.sel.push_back((int)ix);
o.sel_rows.push_back(r.i64());
o.sel_cols.push_back(r.i64());
}
}
o.have_ref = r.u8() != 0;
if (o.have_ref) {
o.ref_n = r.i64();
o.ref_sumsq = r.f64();
o.ref_nonfinite = r.i64();
o.sample = r.f32v();
}
c.opd.push_back(std::move(o));
}
cases.push_back(std::move(c));
}
const bool ok = r.ok;
std::fclose(f);
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. */
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);
auto do_block = [&](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 ss = 0;
int64_t nf = 0;
for (int64_t i = lo; i < hi; ++i) {
if (!std::isfinite(v[i])) { ++nf; continue; }
ss += (double)v[i] * (double)v[i];
}
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();
}
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]; }
*sumsq = ss;
*nonfinite = nf;
std::vector<int64_t> pos;
kf_sample_positions(seed, n, &pos);
sample->clear();
sample->reserve(pos.size());
for (int64_t p : pos) sample->push_back(v[p]);
}
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;
/* 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);
std::vector<float> tmp;
/* A BIG OPERAND IS DRAWN IN BLOCKS AND NEVER MATERIALISES AS FLOATS.
*
* 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) {
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));
}
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. */
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. */
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. */
uint64_t s2 = seed;
const int64_t range = d.idx_max > 0 ? d.idx_max : n;
std::vector<int32_t> pool((size_t)range);
for (int64_t i = 0; i < range; ++i) pool[(size_t)i] = (int32_t)i;
for (int64_t i = 0; i < n && i < range; ++i) {
const int64_t j = i + (int64_t)(rad_splitmix(s2) % (uint64_t)(range - i));
std::swap(pool[(size_t)i], pool[(size_t)j]);
tmp[(size_t)i] = (float)pool[(size_t)i];
}
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;
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);
} else {
rad_fill_normal(tmp.data(), n, seed, 1.0f);
/* INTO THE OPERAND'S DOMAIN, where a normal draw is outside it. */
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]));
} 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. */
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;
for (int64_t t = 0; t < rows; ++t)
for (int64_t h = 0; h < heads; ++h)
for (int64_t j = 0; j < ch; ++j) {
const size_t i = (size_t)((t * heads + h) * ch + j);
const int64_t diag = t % ch;
if (j > diag) tmp[i] = 0.0f;
else if (j == diag) tmp[i] = 1.0f;
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. */
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;
for (int64_t h = 0; h < heads; ++h) {
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)]));
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. */
const int64_t w = d.shape.empty() ? n : d.shape.back();
if (w > 0) {
for (int64_t r = 0; r + w <= n; r += w) {
double ss = 0;
for (int64_t i = 0; i < w; ++i)
ss += (double)tmp[(size_t)(r + i)] * (double)tmp[(size_t)(r + i)];
const float inv = ss > 0 ? (float)(1.0 / std::sqrt(ss)) : 0.0f;
for (int64_t i = 0; i < w; ++i) tmp[(size_t)(r + i)] *= inv;
}
}
}
}
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 {
void kf_operand_enc(const WeightInfo& w, KfOperand* d) {
d->has_enc = true;
d->enc = w.enc;
d->sel.assign(w.sel, w.sel + w.n_sel);
d->sel_rows.assign(w.sel_rows, w.sel_rows + w.n_sel);
d->sel_cols.assign(w.sel_cols, w.sel_cols + w.n_sel);
}
namespace {
/* The entries of the codebook `codes` index, or 0 when they index none. */
int64_t codebook_entries(const RadEncoding& e) {
if (const RadEncPlane* g = rad_enc_plane(&e, "grid")) return g->extent[0];
if (const RadEncPlane* t = rad_enc_plane(&e, "table")) return t->extent[1];
return 0;
}
/* One plane, rows of `rb` bytes. */
void draw_plane(const RadEncoding& e, const RadEncPlane& p, int64_t rows, int64_t cols,
int64_t rb, uint64_t seed, uint8_t* out) {
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 */
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;
for (int64_t j = cols - 1; j > 0; --j)
std::swap(v[(size_t)j], v[(size_t)(rad_splitmix(s) % (uint64_t)(j + 1))]);
for (int64_t j = 0; j < cols; ++j)
rad_store_f32(out + r * rb, p.dtype, j, (float)v[(size_t)j]);
}
return;
}
int sgn = 0;
const int pb = rad_dtype_packed_int(p.dtype, &sgn);
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 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;
if (entries > 0 && (uint64_t)entries < range) range = (uint64_t)entries;
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; }
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);
}
return;
}
if (p.dtype == RAD_E8M0) {
/* 2^-4 .. 2^4: a block scale, which a draw over every exponent would make an 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). */
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);
}
}
} /* namespace */
void kf_draw_planes(const KfOperand& d, uint64_t seed, std::vector<std::vector<uint8_t>>* out) {
out->assign(d.sel.size(), {});
for (size_t k = 0; k < d.sel.size(); ++k) {
const RadEncPlane& p = d.enc.plane[d.sel[k]];
const int64_t rows = d.sel_rows[k], cols = d.sel_cols[k];
const int64_t rb = rad_enc_row_bytes(p.dtype, cols);
std::vector<uint8_t>& b = (*out)[k];
b.assign((size_t)(rows * rb), 0);
uint64_t ps = seed ^ (0xA24BAED4963EE407ull * (uint64_t)(d.sel[k] + 1));
draw_plane(d.enc, p, rows, cols, rb, rad_splitmix(ps), b.data());
}
}
int kf_planes_logical(const KfOperand& d, const std::vector<std::vector<uint8_t>>& planes,
std::vector<uint8_t>* out, std::string* why) {
const int64_t n = rad_numel(d.shape);
out->assign((size_t)rad_dtype_bytes(d.dtype, n), 0);
const void* data[RAD_ENC_MAX_PLANES] = {};
for (size_t k = 0; k < planes.size() && k < RAD_ENC_MAX_PLANES; ++k)
data[k] = planes[k].data();
return enc_selection_logical(d.enc, d.sel.data(), (int)d.sel.size(), d.sel_rows.data(),
d.sel_cols.data(), data, d.dtype, n, out->data(), why);
}
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) {
if (!info || !info->layout || !d.has_enc) return RAD_E_UNSUPPORTED;
RadTensor pt[RAD_ENC_MAX_PLANES];
const int n = (int)d.sel.size();
for (int k = 0; k < n; ++k) {
pt[k] = RadTensor{};
pt[k].data = const_cast<uint8_t*>(planes[(size_t)k].data());
pt[k].dtype = d.enc.plane[d.sel[(size_t)k]].dtype;
pt[k].rank = 2;
pt[k].shape[0] = d.sel_rows[(size_t)k];
pt[k].shape[1] = d.sel_cols[(size_t)k];
rad_tensor_pack(&pt[k]);
}
*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. */
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)
if (!d.shape.empty() && d.shape[0] > v) v = d.shape[0];
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. */
void kf_describe_laid(const KfOperand& d, const RadLayout& lay, void* data, RadTensor* out) {
*out = RadTensor{};
out->data = data;
out->dtype = lay.dtype;
out->rank = (uint32_t)d.shape.size();
for (size_t i = 0; i < d.shape.size() && i < RAD_MAX_RANK; ++i)
out->shape[i] = d.shape[i];
rad_tensor_pack(out);
}
} /* namespace rad */
+221
View File
@@ -0,0 +1,221 @@
/* kfixture.h -- the recorded reference a kernel library is checked against, with no model in the
* room.
*
* 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.
*
* 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.
*
* 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 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.
*/
#pragma once
#include "rad_core.h"
#include <cstdint>
#include <string>
#include <vector>
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. */
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. */
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. */
enum {
KF_FILL_NORMAL = 0,
KF_FILL_SIGMOID = 1,
KF_FILL_GATE_CUMSUM = 2,
KF_FILL_TRI_LOWER = 3,
KF_FILL_UNIT_ROW = 4,
};
/* 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. */
struct KfParam {
std::string key;
int kind = 0; /* RAD_P_INT | RAD_P_F64 | RAD_P_STR */
long long i = 0;
double d = 0;
std::string s;
};
struct KfOperand {
int role = 0;
uint32_t dtype = 0;
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. */
int fill = 0;
bool is_index = false, idx_unique = false, idx_cu = false;
int64_t idx_max = 0, idx_const = -1, fill_chunk = 0;
/* 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. */
bool has_enc = false;
RadEncoding enc{};
std::vector<int> sel;
std::vector<int64_t> sel_rows, sel_cols;
/* The reference, for OUT and INOUT operands of a case that has one. */
bool have_ref = false;
int64_t ref_n = 0;
double ref_sumsq = 0;
int64_t ref_nonfinite = 0;
std::vector<float> sample; /* KF_SAMPLES values at seed-derived positions */
};
struct KfCase {
std::string op;
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. */
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. */
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;
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;
int load(const std::string& path);
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. */
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. */
uint64_t kf_operand_seed(uint64_t case_seed, int 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.
*/
/* 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. */
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).
* RAD_OK, or the refusal with `why`. */
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. */
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. */
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. */
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. */
int64_t kf_vocab_rows(const std::vector<KfOperand>& opd);
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. */
void kf_reduce(const float* v, int64_t n, uint64_t seed, double* sumsq, int64_t* nonfinite,
std::vector<float>* sample);
} /* namespace rad */
+99
View File
@@ -0,0 +1,99 @@
#!/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.
#
# 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.
set -e
[ $# -ge 3 ] || { echo "usage: $0 <docs/OPS.md> <rad-schemas> <plugin.so>..." >&2; exit 2; }
doc=$1; schemas=$2; shift 2
[ -r "$doc" ] || { echo " SKIP no $doc"; exit 77; }
[ -x "$schemas" ] || { echo " SKIP no rad-schemas at $schemas"; exit 77; }
dump=$(mktemp); trap 'rm -f "$dump"' EXIT
for so in "$@"; do
[ -r "$so" ] || { echo " SKIP no plugin at $so"; exit 77; }
"$schemas" "$so" >> "$dump" 2>/dev/null || { echo " SKIP $so would not dump"; exit 77; }
done
awk -v doc="$doc" '
# ---- tool notation: name:type[/optional|/derived], name:role[?] ----------------------------
function t_param(t, f,o) {
if (sub(/\/optional$/, "", t)) o = "/opt"; else if (sub(/\/derived$/, "", t)) o = "/der"
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.
if (sub(/:wtab$/, "", t)) w = "wt"
if (sub(/:weight$/, "", t)) w = "w"
if (sub(/:inout$/, "", t)) io = ":inout"
sub(/:(in|out)$/, "", t); return t w io q }
# ---- doc notation: `name` followed by its annotations -------------------------------------
function d_name(t, a) { a = index(substr(t, 2), "`"); return substr(t, 2, a - 1) }
function d_rest(t, a) { a = index(substr(t, 2), "`"); return substr(t, a + 2) }
function d_param(t, n,r,f,o) {
if (substr(t, 1, 1) != "`") return ""
n = d_name(t); r = d_rest(t); sub(/\(range\)/, "", r)
f = (r ~ /:f64/) ? ":f64" : ""
if (r ~ /\/opt/) o = "/opt"; else if (r ~ /\/der/) o = "/der"
return n f o }
function d_opd(t, n,r,w,io,q) {
if (substr(t, 1, 1) != "`") return ""
n = d_name(t); r = d_rest(t)
if (substr(r, 1, 2) == "wt") w = "wt"; else if (substr(r, 1, 1) == "w") w = "w"
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) -------
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)
if (!(op in P)) P[op] = s; next }
if ($0 ~ /^ operands /) { s = ""; for (i = 2; i <= NF; i++) s = s (i > 2 ? " " : "") t_opd($i)
if (!(op in O)) O[op] = s; next }
next }
# ---- the doc rows --------------------------------------------------------------------------
/^\| `/ {
n = split($0, c, "|")
op = d_name(gensub(/^ +| +$/, "", "g", c[2])); documented[op] = 1
if (n > 5) { exempt++; printf "exempt %-24s line %d -- %s\n", op, FNR,
gensub(/^ +| +$/, "", "g", c[5]); next }
pc = c[3]; oc = c[4]; gsub(/[,;]/, " ", pc); gsub(/[,;]|→/, " ", oc)
ps = ""; np = split(pc, pa, /[ \t]+/)
for (i = 1; i <= np; i++) { v = d_param(pa[i]); if (v != "") ps = ps (ps == "" ? "" : " ") v }
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.
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] }
if (os != O[op]) { ok = 0; printf "OPERAND %-24s line %d\n doc %s\n real %s\n", op, FNR, os, O[op] }
if (!ok) bad++ }
END {
for (op in seen) if (!(op in documented)) {
bad++; printf "UNDOCUMENTED %-20s declared by a plugin, in no table\n", op }
if (unchecked) printf "\n%d op(s) no loaded plugin declares, so unchecked here: %s\n",
unchecked, u_list
printf "\n%s: %d rows, %d exempt, %d unchecked, %d disagree\n", doc, rows, exempt, unchecked, bad
exit bad ? 1 : 0 }
' "$dump" "$doc"
+347
View File
@@ -0,0 +1,347 @@
/* opshapes.cpp -- the non-inline half of opshapes.h: dtype widening and the seeded fill.
*
* 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.
*/
#include "opshapes.h"
#include <thread>
#include <cmath>
#include <cstring>
namespace rad {
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) {
case RAD_F32:
std::memcpy(out->data(), src, (size_t)n * 4);
break;
case RAD_BF16:
for (int64_t i = 0; i < n; ++i) {
const uint32_t b = (uint32_t)((const uint16_t*)src)[i] << 16;
float f;
std::memcpy(&f, &b, 4);
(*out)[(size_t)i] = f;
}
break;
case RAD_F16:
for (int64_t i = 0; i < n; ++i) {
const uint16_t h = ((const uint16_t*)src)[i];
const uint32_t sign = (uint32_t)(h & 0x8000u) << 16;
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. */
if (m == 0) bits = sign;
else {
int sh = -1;
uint32_t mm = m;
do { mm <<= 1; ++sh; } while ((mm & 0x400) == 0);
bits = sign | ((uint32_t)(112 - sh) << 23) | ((mm & 0x3FF) << 13);
}
} else if (e == 0x1F) {
bits = sign | 0x7F800000u | (m << 13);
} else {
bits = sign | ((e + 112) << 23) | (m << 13);
}
float f;
std::memcpy(&f, &bits, 4);
(*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. */
case RAD_F8E4M3:
for (int64_t i = 0; i < n; ++i) {
const uint8_t b = ((const uint8_t*)src)[i];
const uint32_t sign = (uint32_t)(b & 0x80u) << 24;
const uint32_t e = (b >> 3) & 0xFu, m = b & 0x7u;
uint32_t bits;
if (e == 0) {
if (m == 0) bits = sign;
else { /* subnormal: m * 2^-9 */
int sh = -1;
uint32_t mm = m;
do { mm <<= 1; ++sh; } while ((mm & 0x8u) == 0);
bits = sign | ((uint32_t)(127 - 6 - sh) << 23) | ((mm & 0x7u) << 20);
}
} else if (e == 0xFu && m == 0x7u) {
bits = sign | 0x7FC00000u; /* the one NaN encoding */
} else {
bits = sign | ((e + 127 - 7) << 23) | (m << 20);
}
float f;
std::memcpy(&f, &bits, 4);
(*out)[(size_t)i] = f;
}
break;
case RAD_F8E5M2:
for (int64_t i = 0; i < n; ++i) {
const uint8_t b = ((const uint8_t*)src)[i];
const uint32_t sign = (uint32_t)(b & 0x80u) << 24;
const uint32_t e = (b >> 2) & 0x1Fu, m = b & 0x3u;
uint32_t bits;
if (e == 0) {
if (m == 0) bits = sign;
else {
int sh = -1;
uint32_t mm = m;
do { mm <<= 1; ++sh; } while ((mm & 0x4u) == 0);
bits = sign | ((uint32_t)(127 - 14 - sh) << 23) | ((mm & 0x3u) << 21);
}
} else if (e == 0x1Fu) {
bits = sign | 0x7F800000u | (m << 21);
} else {
bits = sign | ((e + 127 - 15) << 23) | (m << 21);
}
float f;
std::memcpy(&f, &bits, 4);
(*out)[(size_t)i] = f;
}
break;
case RAD_I8:
for (int64_t i = 0; i < n; ++i) (*out)[(size_t)i] = (float)((const int8_t*)src)[i];
break;
case RAD_U8:
for (int64_t i = 0; i < n; ++i) (*out)[(size_t)i] = (float)((const uint8_t*)src)[i];
break;
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). */
case RAD_I16:
for (int64_t i = 0; i < n; ++i) (*out)[(size_t)i] = (float)((const int16_t*)src)[i];
break;
case RAD_I64:
for (int64_t i = 0; i < n; ++i) (*out)[(size_t)i] = (float)((const int64_t*)src)[i];
break;
case RAD_U32:
for (int64_t i = 0; i < n; ++i) (*out)[(size_t)i] = (float)((const uint32_t*)src)[i];
break;
case RAD_BOOL:
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. */
break;
}
}
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. */
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;
case RAD_F16:
for (int64_t i = 0; i < n; ++i) {
uint32_t x;
std::memcpy(&x, &src[i], 4);
const uint32_t sign = (x >> 16) & 0x8000u;
int32_t e = (int32_t)((x >> 23) & 0xFF) - 127 + 15;
const uint32_t m = x & 0x7FFFFF;
uint16_t h;
if (e >= 0x1F) h = (uint16_t)(sign | 0x7C00u);
else if (e <= 0) h = (uint16_t)sign;
else h = (uint16_t)(sign | ((uint32_t)e << 10) | (m >> 13));
((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. */
case RAD_F8E4M3:
for (int64_t i = 0; i < n; ++i) {
float a = src[i] < 0 ? -src[i] : src[i];
uint32_t sb;
std::memcpy(&sb, &src[i], 4);
const uint8_t sign = (uint8_t)((sb >> 24) & 0x80u);
if (!(a > 0.0f)) { ((uint8_t*)dst)[i] = sign; continue; }
if (a > 448.0f) a = 448.0f;
if (a >= 0x1p-6f) {
uint32_t u;
std::memcpy(&u, &a, 4);
int e = (int)((u >> 23) & 0xFFu) - 127;
uint32_t mm = (u & 0x7FFFFFu) >> 20;
const uint32_t rem = u & 0xFFFFFu, half = 1u << 19;
if (rem > half || (rem == half && (mm & 1u))) { if (++mm == 8u) { mm = 0; ++e; } }
if (e > 8) { e = 8; mm = 7; }
((uint8_t*)dst)[i] = (uint8_t)(sign | ((uint32_t)(e + 7) << 3) | mm);
} else {
const float scaled = a * 512.0f;
uint32_t m = (uint32_t)(scaled + 0.5f);
if ((float)m - scaled == 0.5f && (m & 1u)) --m;
((uint8_t*)dst)[i] = m > 7u ? (uint8_t)(sign | (1u << 3)) : (uint8_t)(sign | m);
}
}
break;
case RAD_F8E5M2:
for (int64_t i = 0; i < n; ++i) {
uint32_t x;
std::memcpy(&x, &src[i], 4);
const uint32_t sign = (x >> 24) & 0x80u;
int32_t e = (int32_t)((x >> 23) & 0xFF) - 127 + 15;
const uint32_t m = x & 0x7FFFFF;
uint8_t h;
if (e >= 0x1F) h = (uint8_t)(sign | 0x7Cu);
else if (e <= 0) h = (uint8_t)sign;
else h = (uint8_t)(sign | ((uint32_t)e << 2) | (m >> 21));
((uint8_t*)dst)[i] = h;
}
break;
case RAD_I8:
for (int64_t i = 0; i < n; ++i) {
float v = src[i] * 32.0f;
v = v < -127.f ? -127.f : (v > 127.f ? 127.f : v);
((int8_t*)dst)[i] = (int8_t)std::lrintf(v);
}
break;
case RAD_U8:
for (int64_t i = 0; i < n; ++i) {
float v = src[i];
v = v < 0.f ? 0.f : (v > 255.f ? 255.f : v);
((uint8_t*)dst)[i] = (uint8_t)std::lrintf(v);
}
break;
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.
*
* `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. */
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;
case RAD_U32:
for (int64_t i = 0; i < n; ++i) {
const float v = src[i] < 0.f ? 0.f : src[i];
((uint32_t*)dst)[i] = (uint32_t)std::llrintf(v);
}
break;
case RAD_BOOL:
for (int64_t i = 0; i < n; ++i) ((uint8_t*)dst)[i] = src[i] != 0.0f ? 1u : 0u;
break;
default:
std::memset(dst, 0, (size_t)rad_dtype_bytes(dtype, n));
break;
}
}
uint64_t rad_case_seed(uint64_t base, std::string_view op, int band, int domain, int operand) {
uint64_t h = base ^ 0xCBF29CE484222325ull;
for (char c : op) { h ^= (unsigned char)c; h *= 0x100000001B3ull; }
h ^= (uint64_t)band * 0x9E37u; h *= 0x100000001B3ull;
h ^= (uint64_t)domain * 0x85EBu; h *= 0x100000001B3ull;
h ^= (uint64_t)operand * 0xC2B2u; h *= 0x100000001B3ull;
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.
*
* 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.
*/
const int64_t RAD_FILL_BLOCK = 1 << 16;
static void fill_block(float* p, int64_t n, uint64_t seed, float sigma) {
uint64_t s = seed;
for (int64_t i = 0; i < n; i += 2) {
const double u1 = ((double)(rad_splitmix(s) >> 11) + 1.0) * (1.0 / 9007199254740992.0);
const double u2 = ((double)(rad_splitmix(s) >> 11)) * (1.0 / 9007199254740992.0);
const double r = std::sqrt(-2.0 * std::log(u1)), t = 6.283185307179586 * u2;
p[i] = (float)((double)sigma * r * std::cos(t));
if (i + 1 < n) p[i + 1] = (float)((double)sigma * r * std::sin(t));
}
}
static uint64_t block_seed(uint64_t seed, int64_t b) {
uint64_t s = seed ^ (0x9E3779B97F4A7C15ull * (uint64_t)(b + 1));
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. */
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);
}
});
}
for (auto& x : th) x.join();
}
} /* namespace rad */
+502
View File
@@ -0,0 +1,502 @@
/* opshapes.h -- how big is operand i of this op, given its resolved geometry.
*
* THE ONE PLACE THE TOOLS KNOW SOMETHING ABOUT AN OP, AND THEY SHOULD NOT HAVE TO.
*
* 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.
*/
#pragma once
#include "iface.h"
#include <cstring>
#include <string>
#include <vector>
namespace rad {
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. */
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. */
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. */
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. */
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 };
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. */
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. */
struct ShapeCtx {
int64_t n_head_k = 0; /* linear_num_key_heads */
int64_t n_head_v = 0; /* linear_num_value_heads */
int64_t n_seq = 1; /* sequences in the checked batch */
};
/* ================================================================== 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.
*
* WHICH kernel to ask is a real choice and it is the caller's:
*
* - 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;
}
/* 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");
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 tile */
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, which is the form docs/OPS.md
* draws and the only one a one-shot kernel needs, but libr4d's two-shot rows are not safe
* in place and cannot be checked at all without it, so it is passed. */
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;
}
inline int64_t rad_numel(const std::vector<int64_t>& s) {
int64_t n = 1;
for (int64_t d : s) n *= d;
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. */
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);
/* splitmix64, keyed per case so one case's inputs do not depend on how many ran before it. */
inline uint64_t rad_splitmix(uint64_t& x) {
uint64_t z = (x += 0x9E3779B97F4A7C15ull);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
return z ^ (z >> 31);
}
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. */
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);
} /* namespace rad */
+410
View File
@@ -0,0 +1,410 @@
/* rad-chatparse -- the reply parser's acceptance run, against a checkpoint's real tokenizer and
* chat template.
*
* rad-chatparse <fixtures root> the three served models by their folders
* rad-chatparse --model qwen3.8=<dir> [--model ...] one folder per model, named explicitly
* [--fuzz N] random replies per model and request (default 300)
* [--long a,b,c] reply sizes the legacy path is timed at (default 4096,16384,65536)
* [--new-long a,b] sizes only the streaming parser is timed at (default 262144,1048576)
*
* A folder holds the checkpoint's tokenizer.json and chat_template.jinja. The model names are
* the ones tests/legacy/chatdiff.h knows -- qwen3.8, qwen3.6, minicpm5 -- which fix the BOS/EOS
* 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:
*
* * 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.
*
* 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.
*
* Exit status is non-zero when any reply breaks the contract or a verdict is not allowed. */
#include "chatdiff.h"
#include "server/adapters.h"
#include "server/oai.h"
#include "text/tokenizer.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <map>
#include <memory>
#include <random>
#include <sstream>
#include <string>
#include <sys/stat.h>
#include <vector>
using namespace rad;
using namespace rad::chatdiff;
using clk = std::chrono::steady_clock;
namespace {
std::string slurp(const std::string& p) {
std::ifstream f(p);
std::ostringstream ss;
ss << f.rdbuf();
return ss.str();
}
bool is_dir(const std::string& p) {
struct stat st;
return stat(p.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
}
double since(clk::time_point t0) {
return std::chrono::duration<double>(clk::now() - t0).count();
}
std::vector<size_t> sizes(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;
}
return v;
}
/* A model's real tokenizer, and the pieces the server's decoder hands a reply to the parser in. */
struct Tok {
std::shared_ptr<Vocab> vocab;
Tokenizer tok;
int load(const std::string& dir, std::string* why) {
VocabBuild vb;
if (parse_tokenizer_json((dir + "/tokenizer.json").c_str(), vb) < 0) {
*why = "tokenizer.json did not load";
return RAD_E_FORMAT;
}
vocab = std::make_shared<Vocab>();
if (vocab->load(std::move(vb)) < 0) { *why = "the vocabulary did not load"; return RAD_E_FORMAT; }
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. */
std::vector<std::string> pieces(const std::string& text,
const std::vector<std::string>& preserved) const {
std::vector<int32_t> ids;
tok.encode(text, ids, /*add_special=*/false, /*parse_special=*/true);
Detokenizer d(vocab, {}, /*render_special=*/false, preserved);
std::vector<std::string> out;
for (int32_t id : ids) {
std::string p = d.push(id);
if (!p.empty()) out.push_back(std::move(p));
}
std::string tail = d.flush();
if (!tail.empty()) out.push_back(std::move(tail));
return out;
}
};
struct Tally {
int replies = 0, same = 0, recovered = 0, bare_lift = 0, violations = 0;
int decoder_changed = 0; /* the decoded text is not the text: a control token not preserved */
int old_stream_disagrees = 0;
int shown = 0, markers_lost = 0;
size_t tokens = 0, bytes = 0;
double t_new = 0, t_old = 0;
};
/* The legacy path's stream: the accumulated reply re-parsed at every token and the growth
* sent. Returns whether what it sent adds up to its own buffered answer. */
bool old_stream_agrees(const Bench& b, const std::vector<std::string>& pieces, double* secs) {
legacy::LegacyDeltaStream s(b.old_parser(), b.request().tools, b.model().terminators);
std::string acc;
const auto t0 = clk::now();
for (size_t i = 0; i < pieces.size(); ++i) {
acc += pieces[i];
s.push(acc, false);
}
s.push(acc, true);
*secs += since(t0);
const legacy::Answer a = b.old_parse(acc);
if (s.content() != a.content || s.reasoning() != a.reasoning || s.names().size() != a.calls.size())
return false;
for (size_t i = 0; i < a.calls.size(); ++i)
if (s.names()[i] != a.calls[i].name || s.arguments()[i] != a.calls[i].arguments) return false;
return true;
}
void check_reply(const Bench& b, const Tok& t, const std::string& written, const char* what,
Tally* ty) {
const std::vector<std::string> pieces = t.pieces(written, b.prompt().preserved_tokens);
std::string text;
std::vector<size_t> cuts;
for (const std::string& p : pieces) {
text += p;
cuts.push_back(text.size());
}
++ty->replies;
ty->tokens += pieces.size();
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. */
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))
terms.push_back({ at, at + t.size() });
auto count = [&terms](const std::string& s, const std::string& m, bool skip_terms) {
size_t n = 0;
for (size_t at = s.find(m); at != std::string::npos; at = s.find(m, at + 1)) {
bool inside = false;
for (const auto& [a, e] : terms)
inside = inside || (skip_terms && at < e && a < at + m.size());
if (!inside) ++n;
}
return n;
};
for (const std::string& m : b.prompt().preserved_tokens) {
if (count(text, m, false) >= count(written, m, true)) continue;
++ty->markers_lost;
if (ty->shown++ < 5)
std::fprintf(stderr, " the decoder lost the marker %s:\n written: %s\n",
nlohmann::json(m).dump().c_str(),
nlohmann::json(written).dump(-1, ' ', false,
nlohmann::json::error_handler_t::replace).c_str());
break;
}
}
const Verdict v = compare(b, text);
const std::string j = judge(v);
if (!j.empty()) {
++ty->violations;
std::fprintf(stderr, " VIOLATION %s [%s, %s]: %s\n reply: %s\n%s\n", what,
b.model().name.c_str(), describe(b.request()).c_str(), j.c_str(),
nlohmann::json(text).dump(-1, ' ', false,
nlohmann::json::error_handler_t::replace).c_str(),
v.detail.c_str());
}
if (v.same) ++ty->same;
else if (v.bare_lift) ++ty->bare_lift;
else ++ty->recovered;
const ReplyMessage expect = reply_parse(b.parser(), text);
const auto t0 = clk::now();
const std::string s = check_stream(b.parser(), text, cuts, expect);
ty->t_new += since(t0);
if (!s.empty()) {
++ty->violations;
std::fprintf(stderr, " STREAM %s [%s, %s]: %s\n", what, b.model().name.c_str(),
describe(b.request()).c_str(), s.c_str());
}
if (!old_stream_agrees(b, pieces, &ty->t_old)) ++ty->old_stream_disagrees;
}
/* ------------------------------------------------------------------ the long-reply timing */
struct Timing { double sse = 0, parser = 0; };
Timing time_new(const Bench& b, const std::vector<std::string>& pieces, int reps) {
Timing best{ 1e30, 1e30 };
server::ReplyParserBridge bridge(b.parser_ptr());
for (int r = 0; r < reps; ++r) {
server::OaiRequest req;
req.id = "chatcmpl-acceptance";
req.model = b.model().name;
req.parse_tools = true;
auto t0 = clk::now();
{
server::ChatDeltaStream st(req, 0, &bridge);
size_t n = st.first_chunk().size();
for (const std::string& p : pieces) n += st.push(p, false).size();
n += st.final_chunk(server::Finish::Stop).size();
if (n == 0) std::fprintf(stderr, "no output\n");
}
best.sse = std::min(best.sse, since(t0));
t0 = clk::now();
std::unique_ptr<ReplyStream> s = b.parser().open();
std::vector<ReplyEvent> ev;
for (const std::string& p : pieces) {
s->feed(p, &ev);
ev.clear();
}
s->finish(&ev);
best.parser = std::min(best.parser, since(t0));
}
return best;
}
Timing time_old(const Bench& b, const std::vector<std::string>& pieces) {
Timing t;
auto t0 = clk::now();
{
legacy::LegacyDeltaStream s(b.old_parser(), true, b.model().terminators);
std::string acc;
for (const std::string& p : pieces) {
acc += p;
s.push(acc, false);
}
s.push(acc, true);
}
t.sse = since(t0);
t0 = clk::now();
std::string acc;
for (const std::string& p : pieces) {
acc += p;
(void)b.old_parse(acc, true);
}
(void)b.old_parse(acc, false);
t.parser = since(t0);
return t;
}
} /* namespace */
int main(int argc, char** argv) {
std::vector<std::pair<std::string, std::string>> want; /* model name, folder */
int fuzz = 300;
std::vector<size_t> old_sizes = { 4096, 16384, 65536 };
std::vector<size_t> new_sizes = { 262144, 1048576 };
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
if (a == "--model" && i + 1 < argc) {
const std::string v = argv[++i];
const size_t eq = v.find('=');
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]);
} else if (a == "--long" && i + 1 < argc) {
old_sizes = sizes(argv[++i]);
} else if (a == "--new-long" && i + 1 < argc) {
new_sizes = sizes(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" } },
{ "qwen3.6", { "Qwen3.6-35B-A3B-FP8" } },
{ "minicpm5", { "MiniCPM5-2B" } },
};
for (const auto& [name, dirs] : layout)
for (const char* d : dirs)
if (is_dir(a + "/" + d)) { want.push_back({ name, a + "/" + d }); break; }
} else {
std::fprintf(stderr, "usage: rad-chatparse <fixtures root> | --model name=dir ... "
"[--fuzz N] [--long a,b] [--new-long a,b]\n");
return 2;
}
}
if (want.empty()) {
std::fprintf(stderr, "rad-chatparse: no model folders found\n");
return 2;
}
log_set_level(Log::Warn);
int violations = 0;
for (const auto& [name, dir] : want) {
const Model* m = nullptr;
for (const Model& k : models()) if (k.name == name) m = &k;
if (!m) { std::fprintf(stderr, "unknown model '%s'\n", name.c_str()); return 2; }
std::printf("== %s (%s)\n", m->name.c_str(), dir.c_str());
Tok tk;
std::string why;
if (tk.load(dir, &why) < 0) { std::fprintf(stderr, " %s\n", why.c_str()); return 1; }
const std::string jinja = slurp(dir + "/chat_template.jinja");
std::printf(" tokenizer: %d tokens; template: %zu bytes\n", tk.vocab->n_tokens(),
jinja.size());
const std::vector<ChatRequest> reqs = [] {
std::vector<ChatRequest> v(4);
v[1].thinking = false;
v[2].parallel = false;
v[3].reasoning = false;
return v;
}();
Tally ty;
std::mt19937 rng(20260924);
const std::vector<std::string> frag = fragments(*m);
for (const ChatRequest& rq : reqs) {
Bench b;
if (b.load(*m, jinja, &why) < 0 || b.bind(rq, agent_tools(), &why) < 0) {
std::fprintf(stderr, " %s: %s\n", describe(rq).c_str(), why.c_str());
return 1;
}
std::vector<std::string> seeds;
for (const ojson& msg : rendered_corpus()) {
const std::string r = b.render_reply(msg);
if (r.empty()) continue;
seeds.push_back(r);
check_reply(b, tk, r, "rendered", &ty);
}
for (const Adversarial& a : adversarial(*m)) {
seeds.push_back(a.text);
check_reply(b, tk, a.text, a.name.c_str(), &ty);
}
for (int i = 0; i < fuzz && !seeds.empty(); ++i) {
std::string text;
if (i % 2 == 0) {
const int n = (int)(rng() % 24);
for (int k = 0; k < n; ++k) text += frag[rng() % frag.size()];
} else {
text = mutate(rng, seeds[rng() % seeds.size()], frag);
}
check_reply(b, tk, sanitize(text), "fuzz", &ty);
}
}
violations += ty.violations;
std::printf(" %d replies, %zu tokens, %zu bytes: %d identical to the old path, %d "
"recovered where the old grammar failed, %d bare calls the old lifter took "
"from content; %d contract violations\n",
ty.replies, ty.tokens, ty.bytes, ty.same, ty.recovered, ty.bare_lift,
ty.violations);
std::printf(" the decoder dropped a control token outside the format from %d replies and "
"a format marker from %d; the OLD path's own stream disagreed with its "
"buffered answer on %d\n",
ty.decoder_changed - ty.markers_lost, ty.markers_lost, ty.old_stream_disagrees);
violations += ty.markers_lost;
std::printf(" corpus fed token by token: new %.1f ms, old %.1f ms\n", ty.t_new * 1e3,
ty.t_old * 1e3);
/* The cost of a long reply, token by token. */
Bench b;
if (b.load(*m, jinja, &why) < 0 || b.bind(ChatRequest{}, agent_tools(), &why) < 0) return 1;
std::printf(" %9s %8s | %12s %12s %9s | %12s %12s\n", "bytes", "tokens", "old SSE ms",
"new SSE ms", "speedup", "old parse ms", "new parse ms");
for (size_t n : old_sizes) {
const std::string text = long_reply(*m, n);
const std::vector<std::string> p = tk.pieces(text, b.prompt().preserved_tokens);
const Timing o = time_old(b, p);
const Timing nw = time_new(b, p, 5);
std::printf(" %9zu %8zu | %12.2f %12.3f %8.0fx | %12.2f %12.3f\n", text.size(),
p.size(), o.sse * 1e3, nw.sse * 1e3, o.sse / nw.sse, o.parser * 1e3,
nw.parser * 1e3);
}
for (size_t n : new_sizes) {
const std::string text = long_reply(*m, n);
const std::vector<std::string> p = tk.pieces(text, b.prompt().preserved_tokens);
const Timing nw = time_new(b, p, 3);
std::printf(" %9zu %8zu | %12s %12.3f %9s | %12s %12.3f (%.1f ns/byte, %.2f us/token)\n",
text.size(), p.size(), "-", nw.sse * 1e3, "", "-", nw.parser * 1e3,
nw.parser / text.size() * 1e9, nw.parser / p.size() * 1e6);
}
}
std::printf("%s\n", violations ? "FAILED" : "ok");
return violations ? 1 : 0;
}
File diff suppressed because it is too large. Load diff
+783
View File
@@ -0,0 +1,783 @@
/* rad_gbnf_check.cpp -- the GBNF mask engine's acceptance run, on a real vocabulary.
*
* rad-gbnf-check --tokenizer PATH/tokenizer.json --template PATH/chat_template.jinja
* [--tokenizer-config PATH/tokenizer_config.json]
* [--schema FILE.json]... [--gbnf FILE]...
* [--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.
*
* 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:
*
* 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.
*
* 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.
*
* 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.
*/
#include "gbnf_oracle.h"
#include "rad_internal.h"
#include "sample/gbnf.h"
#include "sample/grammar.h"
#include "sample/vocab_view.h"
#include "text/chat.h"
#include "text/tokenizer.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include <unistd.h>
using namespace rad;
using ojson = nlohmann::ordered_json;
using Clock = std::chrono::steady_clock;
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);
*ok = (bool)f;
std::stringstream ss;
ss << f.rdbuf();
return ss.str();
}
double ms_since(Clock::time_point t0) {
return std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
}
double rss_mib() {
long pages = 0, resident = 0;
FILE* f = std::fopen("/proc/self/statm", "r");
if (!f) return 0.0;
if (std::fscanf(f, "%ld %ld", &pages, &resident) != 2) resident = 0;
std::fclose(f);
return (double)resident * (double)sysconf(_SC_PAGESIZE) / (1024.0 * 1024.0);
}
/* ================================================================== what is measured */
struct Dist {
std::vector<double> v;
void add(double x) { v.push_back(x); }
void merge(const Dist& o) { v.insert(v.end(), o.v.begin(), o.v.end()); }
double q(double p) {
if (v.empty()) return 0.0;
std::sort(v.begin(), v.end());
return v[std::min(v.size() - 1, (size_t)(p * (double)v.size()))];
}
double max() { return v.empty() ? 0.0 : *std::max_element(v.begin(), v.end()); }
double mean() const {
double s = 0.0;
for (double x : v) s += x;
return v.empty() ? 0.0 : s / (double)v.size();
}
std::string line() {
char b[160];
std::snprintf(b, sizeof b, "n=%zu p50 %.3f p99 %.3f max %.3f ms", v.size(), q(0.50),
q(0.99), max());
return b;
}
};
enum class OracleMode { Off, Cold, All };
struct Run {
const RealView* 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. */
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;
const auto t0 = Clock::now();
const int st = g.fill_mask(m, n_words);
const double ms = ms_since(t0);
if (engine_ms) *engine_ms = ms;
const bool computed = g.masks_walked() != w0;
if (oracle == OracleMode::Off) (computed ? (split ? cold_split : cold) : warm).add(ms);
if (oracle == OracleMode::All || (oracle == OracleMode::Cold && computed)) {
std::vector<uint32_t> ref((size_t)n_words);
const int rs = gbnf_oracle_mask(g, ref.data(), n_words);
if (rs != RAD_E_FULL && rs != RAD_E_NOMEM) {
++compared;
const bool same = rs == st &&
(st < 0 || std::memcmp(ref.data(), m, (size_t)n_words * 4) == 0);
if (!same) report(g, m, st, ref.data(), rs, where);
}
}
return st;
}
void report(const GbnfGrammar& g, const uint32_t* m, int st, const uint32_t* ref, int rs,
const char* where) {
++mismatches;
if (mismatches > 8) return;
int64_t only_e = 0, only_o = 0;
std::string ex;
for (int32_t t = 0; t < view->n_tokens(); ++t) {
const bool a = (m[t >> 5] >> (t & 31)) & 1u, b = (ref[t >> 5] >> (t & 31)) & 1u;
if (a == b) continue;
(a ? only_e : only_o)++;
if (only_e + only_o <= 6) {
ex += " ";
ex += a ? "+" : "-";
ex += std::to_string(t) + "'" + escape(view->token_piece(t)) + "'";
}
}
std::printf(" MISMATCH in %s: status %d, oracle %d; %zu stacks, partial {%u,%d}; "
"%lld tokens only the engine admits, %lld only the oracle:%s\n",
where, st, rs, g.stacks().size(), g.partial().value, g.partial().n_remain,
(long long)only_e, (long long)only_o, ex.c_str());
}
static std::string escape(const std::string& s) {
std::string o;
for (unsigned char c : s) {
if (c == '\n') o += "\\n";
else if (c == '\t') o += "\\t";
else if (c < 0x20 || c == 0x7f || c == '\'') {
char b[8];
std::snprintf(b, sizeof b, "\\x%02x", c);
o += b;
} else {
o += (char)c;
}
}
return o;
}
};
/* ================================================================== grammars and texts */
const char* kTools = R"([
{"type":"function","function":{"name":"bash","description":"Run a shell command.",
"parameters":{"type":"object","properties":{
"command":{"type":"string","description":"The command"},
"timeout":{"type":"integer","description":"Timeout in ms"},
"description":{"type":"string","description":"What it does"}},"required":["command"]}}},
{"type":"function","function":{"name":"read_file","description":"Read a file.",
"parameters":{"type":"object","properties":{
"path":{"type":"string"},"offset":{"type":"integer"},"limit":{"type":"integer"}},
"required":["path"]}}},
{"type":"function","function":{"name":"write_file","description":"Write a file.",
"parameters":{"type":"object","properties":{
"path":{"type":"string"},"content":{"type":"string"}},"required":["path","content"]}}},
{"type":"function","function":{"name":"edit_file","description":"Replace a string in a file.",
"parameters":{"type":"object","properties":{
"path":{"type":"string"},"old_string":{"type":"string"},"new_string":{"type":"string"},
"replace_all":{"type":"boolean"}},"required":["path","old_string","new_string"]}}},
{"type":"function","function":{"name":"glob","description":"Find files.",
"parameters":{"type":"object","properties":{
"pattern":{"type":"string"},"path":{"type":"string"}},"required":["pattern"]}}},
{"type":"function","function":{"name":"grep","description":"Search file contents.",
"parameters":{"type":"object","properties":{
"pattern":{"type":"string"},"path":{"type":"string"},"include":{"type":"string"},
"case_sensitive":{"type":"boolean"}},"required":["pattern"]}}},
{"type":"function","function":{"name":"todo_write","description":"Update the todo list.",
"parameters":{"type":"object","properties":{
"todos":{"type":"array","items":{"type":"object","properties":{
"content":{"type":"string"},
"status":{"type":"string","enum":["pending","in_progress","completed"]},
"id":{"type":"string"}},"required":["content","status","id"]}}},"required":["todos"]}}}
])";
std::string go_file() {
std::string s = "package cache\n\nimport (\n\t\"container/list\"\n\t\"sync\"\n)\n\n";
for (int i = 0; i < 12; ++i) {
const std::string n = std::to_string(i);
s += "// Shard" + n + " holds a fixed-capacity LRU keyed by string.\n"
"type Shard" + n + " struct {\n\tmu sync.Mutex\n\tcap int\n"
"\tll *list.List\n\titems map[string]*list.Element\n}\n\n"
"func (s *Shard" + n + ") Get(key string) (any, bool) {\n"
"\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif e, ok := s.items[key]; ok {\n"
"\t\ts.ll.MoveToFront(e)\n\t\treturn e.Value.(*entry).val, true\n\t}\n"
"\treturn nil, false\n}\n\n"
"func (s *Shard" + n + ") Put(key string, val any) {\n"
"\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif e, ok := s.items[key]; ok {\n"
"\t\te.Value.(*entry).val = val\n\t\ts.ll.MoveToFront(e)\n\t\treturn\n\t}\n"
"\tif s.ll.Len() >= s.cap {\n\t\tlast := s.ll.Back()\n\t\ts.ll.Remove(last)\n"
"\t\tdelete(s.items, last.Value.(*entry).key)\n\t}\n"
"\ts.items[key] = s.ll.PushFront(&entry{key: key, val: val})\n}\n\n";
}
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. */
std::vector<std::string> tool_call_texts() {
return {
"<tool_call>\n<function=bash>\n<parameter=command>\n"
"cd /repo && go test ./... 2>&1 | head -50\n</parameter>\n"
"<parameter=description>\nRun the test suite\n</parameter>\n</function>\n</tool_call>",
"<tool_call>\n<function=read_file>\n<parameter=path>\n/repo/cache/lru.go\n</parameter>\n"
"<parameter=limit>\n200\n</parameter>\n</function>\n</tool_call>",
"<tool_call>\n<function=write_file>\n<parameter=path>\n/repo/cache/shards.go\n"
"</parameter>\n"
"<parameter=content>\n" + go_file() + "\n</parameter>\n</function>\n</tool_call>",
"<tool_call>\n<function=edit_file>\n<parameter=path>\n/repo/cache/lru.go\n</parameter>\n"
"<parameter=old_string>\n\tif s.ll.Len() >= s.cap {\n\t\tlast := s.ll.Back()\n"
"\t\ts.ll.Remove(last)\n</parameter>\n<parameter=new_string>\n"
"\tfor s.ll.Len() >= s.cap && s.cap > 0 {\n\t\tlast := s.ll.Back()\n"
"\t\ts.ll.Remove(last)\n\t\tevictions.Add(1)\n</parameter>\n</function>\n</tool_call>",
};
}
/* 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. */
struct SchemaCase { const char* name; const char* schema; std::vector<std::string> docs; };
std::vector<SchemaCase> schema_cases() {
return {
{ "tool-arguments",
R"({"type":"object","properties":{"command":{"type":"string"},
"timeout":{"type":"integer"},
"env":{"type":"object","additionalProperties":{"type":"string"}},
"background":{"type":"boolean"}},"required":["command"]})",
{ R"({"command": "grep -rn \"TODO\" src/ | sort | uniq -c | sort -rn | head -20", )"
R"("timeout": 120000, "env": {"LANG": "C.UTF-8", "PAGER": "cat"}, )"
R"("background": false})" } },
{ "answer-with-sources",
R"({"type":"object","properties":{"answer":{"type":"string"},
"confidence":{"type":"number","minimum":0,"maximum":1},
"sources":{"type":"array","items":{"type":"object","properties":{
"title":{"type":"string"},"url":{"type":"string"},"year":{"type":"integer"}},
"required":["title","url"]}},
"language":{"type":"string","enum":["en","de","ja","zh"]}},
"required":["answer","confidence","sources"]})",
{ "{\"answer\": \"Die Hauptstadt ist Berlin \xe2\x80\x94 seit 1990 wieder, davor Bonn. "
"\xe6\x9d\xb1\xe4\xba\xac\xe3\x81\xaf\xe6\x97\xa5\xe6\x9c\xac\xe3\x81\xae\xe9\xa6\x96"
"\xe9\x83\xbd\xe3\x81\xa7\xe3\x81\x99\xe3\x80\x82 \\\"quoted\\\" \\u00e9\", "
"\"confidence\": 0.93, "
"\"sources\": [{\"title\": \"Einigungsvertrag\", \"url\": \"https://example.org/ev\", "
"\"year\": 1990}, {\"title\": \"Hauptstadtbeschluss\", "
"\"url\": \"https://example.org/hb\"}], "
"\"language\": \"de\"}" } },
{ "records",
R"({"type":"array","items":{"type":"object","properties":{
"id":{"type":"integer"},"name":{"type":"string","minLength":1,"maxLength":40},
"tags":{"type":"array","items":{"type":"string"},"maxItems":5},
"score":{"type":["number","null"]},
"kind":{"oneOf":[{"const":"user"},{"const":"group"}]}},
"required":["id","name","kind"]},"minItems":1})",
{ R"([{"id": 1, "name": "alice", "kind": "user", "tags": ["admin", "ops"], )"
R"("score": 12.5}, {"id": 2, "name": "wheel", "kind": "group", "tags": [], )"
R"("score": null}])" } },
{ "nested-free-form",
R"({"type":"object","properties":{"plan":{"type":"array","items":{
"type":"object","properties":{"step":{"type":"string"},"detail":{}},
"required":["step"]}}},"required":["plan"]})",
{ R"({"plan": [{"step": "read", "detail": {"files": ["a.go", "b.go"], "depth": 2}}, )"
R"({"step": "edit", "detail": {"lines": [1, 2.5e3, true, null, {"k": "v"}]}}, )"
R"({"step": "test"}]})" } },
};
}
/* A few client grammars of the kinds /v1/completions sees. */
struct GbnfCase { std::string name, text; std::vector<std::string> docs; };
std::vector<GbnfCase> gbnf_cases() {
return {
{ "arithmetic",
"root ::= expr\nexpr ::= term ([-+*/] term)*\n"
"term ::= num | \"(\" ws expr ws \")\"\nnum ::= [0-9]+ (\".\" [0-9]+)?\n"
"ws ::= [ \\t\\n]*\n",
{ "(12.5+3)*4-(7/(2+1.25))" } },
{ "csv",
"root ::= header row+\nheader ::= field (\",\" field)* \"\\n\"\n"
"row ::= field (\",\" field)* \"\\n\"\n"
"field ::= [^,\\n\"]* | \"\\\"\" ([^\"] | \"\\\"\\\"\")* \"\\\"\"\n",
{ "name,city,note\nAda,London,\"likes \"\"engines\"\"\"\nLinus,Helsinki,\n" } },
{ "list-of-words",
"root ::= (\"- \" [^\\n]+ \"\\n\"){1,8}\n",
{ "- buy milk\n- r\xc3\xa9sum\xc3\xa9 \xe2\x9c\x93\n"
"- \xe5\x86\x99\xe4\xbd\x9c\xe6\x96\x87\xe4\xbb\xb6\n" } },
};
}
/* ================================================================== driving a grammar */
std::vector<int32_t> admitted(const uint32_t* m, int32_t n_tok, bool with_eog, const VocabView& v) {
std::vector<int32_t> ids;
for (int32_t t = 0; t < n_tok; ++t)
if ((m[t >> 5] >> (t & 31)) & 1u)
if (with_eog || !v.is_eog(t)) ids.push_back(t);
return ids;
}
bool has(const uint32_t* m, int32_t t) { return (m[t >> 5] >> (t & 31)) & 1u; }
uint64_t xorshift(uint64_t& s) {
s ^= s << 13;
s ^= s >> 7;
s ^= s << 17;
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. */
std::string fresh(const std::string& text) {
static int n = 0;
return text + "\n# rad-gbnf-check run " + std::to_string(++n) + "\n";
}
struct Replay {
std::vector<double> step_ms;
uint64_t walks = 0;
int refused = 0; /* tokens of the text the mask did not admit */
};
/* Sampler::build_step's walk at depth-3 speculation, with the true continuation as the drafts:
* every draft verifies, so each step masks four positions and accepts three tokens. */
Replay replay(Run& run, GbnfGrammar& g, const std::vector<int32_t>& toks, const char* where) {
Replay r;
std::vector<uint32_t> m((size_t)run.n_words);
const uint64_t w0 = g.masks_walked();
size_t i = 0;
while (i < toks.size()) {
const int n_pos = (int)std::min<size_t>(4, toks.size() - i);
double ms = 0.0;
auto timed = [&ms](auto&& f) {
const auto t0 = Clock::now();
auto x = f();
ms += ms_since(t0);
return x;
};
const bool walk = n_pos > 1;
if (walk) timed([&] { g.push_state(); return 0; });
bool dead = false;
for (int k = 0; k < n_pos && !dead; ++k) {
if (walk && k > 0 && timed([&] { return g.accept_token(toks[i + k - 1]); }) < 0) {
dead = true;
break;
}
double mask_ms = 0.0;
const int st = run.mask(g, m.data(), where, &mask_ms);
ms += mask_ms;
if (st < 0) { dead = true; break; }
if (!has(m.data(), toks[i + k])) ++r.refused;
}
if (walk) timed([&] { return g.rollback(); });
const int n_acc = (int)std::min<size_t>(3, toks.size() - i);
for (int k = 0; k < n_acc; ++k)
if (timed([&] { return g.accept_token(toks[i + k]); }) < 0) {
++r.refused;
r.walks = g.masks_walked() - w0;
return r;
}
r.step_ms.push_back(ms);
i += (size_t)n_acc;
}
r.walks = g.masks_walked() - w0;
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. */
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 int32_t n_tok = v.n_tokens();
int64_t masks = 0;
for (int w = 0; w < n_walks; ++w) {
std::unique_ptr<GbnfGrammar> g;
std::string err;
if (GbnfGrammar::create(text, "root", &v, false, {}, {}, &g, &err) < 0) return masks;
uint64_t rng = (seed + 1) * 0x9e3779b97f4a7c15ull + (uint64_t)w * 0x632be59bd9b4e019ull;
std::vector<std::vector<uint32_t>> m(4, std::vector<uint32_t>((size_t)run.n_words));
auto pick = [&](const uint32_t* mask, bool admissible) -> int32_t {
if (!admissible) return (int32_t)(xorshift(rng) % (uint64_t)n_tok);
if (xorshift(rng) % 100 < 35) {
std::vector<int32_t> s;
for (int32_t t : run.structural) if (has(mask, t)) s.push_back(t);
if (!s.empty()) return s[xorshift(rng) % s.size()];
}
const auto ids = admitted(mask, n_tok, false, v);
if (ids.empty()) return -1;
return ids[xorshift(rng) % ids.size()];
};
for (int step = 0; step < n_steps; ++step) {
const int n_pos = 1 + (int)(xorshift(rng) % 4);
std::vector<int32_t> d;
g->push_state();
int live = 0;
for (int k = 0; k < n_pos; ++k) {
if (k > 0 && g->accept_token(d[(size_t)k - 1]) < 0) break;
if (run.mask(*g, m[(size_t)k].data(), where) < 0) break;
++masks;
++live;
if (k + 1 < n_pos) d.push_back(pick(m[(size_t)k].data(), xorshift(rng) % 100 < 85));
if (!d.empty() && d.back() < 0) break;
}
g->rollback();
if (live == 0) break;
size_t j = 0;
while ((int)j + 1 < live && j < d.size() && d[j] >= 0 && has(m[j].data(), d[j])) ++j;
bool ok = true;
for (size_t k = 0; k < j && ok; ++k) ok = g->accept_token(d[k]) >= 0;
if (!ok) break;
const int32_t bonus = pick(m[j].data(), true);
if (bonus < 0) break; /* only the end is admissible */
if (g->accept_token(bonus) < 0) break;
}
}
return masks;
}
/* ================================================================== one grammar */
struct Totals {
int64_t compared = 0, mismatches = 0;
Dist cold, cold_split, warm, first_steps;
};
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;
std::printf("\n== %s: %zu bytes of GBNF\n", label.c_str(), text.size());
/* Compile from nothing. */
const std::string fresh_text = fresh(text);
const double rss0 = rss_mib();
const auto t0 = Clock::now();
std::shared_ptr<const GbnfProgram> prog;
std::string err;
const int cs = gbnf_compile(fresh_text, "root", &v, &prog, &err);
const double compile_ms = ms_since(t0);
if (cs < 0) {
std::printf(" REFUSED in %.1f ms: %s\n", compile_ms, err.c_str());
return;
}
const GbnfProgramInfo info = gbnf_program_info(*prog);
std::printf(" compile %.1f ms (mask plan %.1f ms, %.0fM units): %zu rules, %zu mask keys "
"(%zu dense, %zu deep at most), %zu remainder nodes (largest %zu); plan %.2f MiB, "
"resident set +%.1f MiB\n",
compile_ms, info.plan_ms, (double)info.plan_work / 1e6, info.rules, info.keys,
info.dense_masks, info.max_key_depth, info.rem_nodes, info.max_rem_nodes,
(double)info.bytes / (1024.0 * 1024.0), rss_mib() - rss0);
/* The replay texts this grammar admits. */
std::vector<std::vector<int32_t>> texts;
for (const std::string& d : docs) {
std::vector<int32_t> toks;
v.tok().encode(d, toks, false, true);
std::unique_ptr<GbnfGrammar> probe;
if (GbnfGrammar::create(fresh_text, "root", &v, false, {}, {}, &probe, &err) < 0) break;
bool admitted = true;
for (int32_t t : toks) {
if (probe->accept_token(t) < 0) { admitted = false; break; }
}
if (!admitted) {
std::printf(" (a replay text is not admitted by this grammar; walks only)\n");
continue;
}
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. */
Run run;
run.view = base.view;
run.oracle = OracleMode::Off;
run.n_words = base.n_words;
run.structural = base.structural;
for (int pass = 0; pass < passes && !texts.empty(); ++pass) {
Dist steps;
std::string per;
uint64_t walks_n = 0;
int refused = 0;
for (size_t c = 0; c < texts.size(); ++c) {
std::unique_ptr<GbnfGrammar> g;
if (GbnfGrammar::create(fresh_text, "root", &v, false, {}, {}, &g, &err) < 0) break;
const std::string where = label + " replay " + std::to_string(c);
Replay r = replay(run, *g, texts[c], where.c_str());
Dist d;
for (double x : r.step_ms) { d.add(x); steps.add(x); }
if (pass == 0) for (double x : r.step_ms) tot.first_steps.add(x);
char b[200];
std::snprintf(b, sizeof b, "\n text %zu: %zu tokens, %zu steps, %.3f ms/step mean, "
"max %.3f, %llu masks computed", c, texts[c].size(), r.step_ms.size(),
d.mean(), d.max(), (unsigned long long)r.walks);
per += b;
walks_n += r.walks;
refused += r.refused;
}
std::printf(" replay pass %d (%s): %.3f ms/step mean, %s, %llu masks computed%s%s\n",
pass, pass == 0 ? "cold program" : "warm", steps.mean(), steps.line().c_str(),
(unsigned long long)walks_n, refused ? ", TEXT TOKENS REFUSED" : "",
per.c_str());
}
const std::string walk_label = label + " walk";
const int64_t n_masks = walks(run, fresh_text, n_walks, n_steps, seed, walk_label.c_str());
std::printf(" walks: %d x %d steps, %lld masks\n", n_walks, n_steps, (long long)n_masks);
std::printf(" masks computed: %s\n", run.cold.line().c_str());
if (!run.cold_split.v.empty())
std::printf(" ... at a split character: %s\n", run.cold_split.line().c_str());
std::printf(" masks from cache: %s\n", run.warm.line().c_str());
tot.cold.merge(run.cold);
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. */
if (base.oracle == OracleMode::Off) return;
const std::string oracle_text = fresh(text);
Run orc;
orc.view = base.view;
orc.oracle = base.oracle;
orc.n_words = base.n_words;
orc.structural = base.structural;
for (size_t c = 0; c < texts.size(); ++c) {
std::unique_ptr<GbnfGrammar> g;
if (GbnfGrammar::create(oracle_text, "root", &v, false, {}, {}, &g, &err) < 0) break;
replay(orc, *g, texts[c], (label + " replay " + std::to_string(c)).c_str());
}
walks(orc, oracle_text, n_walks, n_steps, seed, (label + " walk").c_str());
std::printf(" oracle: %lld states compared, %lld mismatches\n", (long long)orc.compared,
(long long)orc.mismatches);
tot.compared += orc.compared;
tot.mismatches += orc.mismatches;
}
void usage() {
std::fprintf(stderr,
"usage: rad-gbnf-check --tokenizer PATH/tokenizer.json "
"--template PATH/chat_template.jinja\n"
" [--tokenizer-config PATH] [--schema FILE.json]... [--gbnf FILE]...\n"
" [--walks N] [--walk-steps N] [--passes N] [--seed N]\n"
" [--oracle cold|all|off]\n");
}
} /* namespace */
int main(int argc, char** argv) {
std::string tok_path, tpl_path, cfg_path;
std::vector<std::string> schema_files, gbnf_files;
int n_walks = 6, n_steps = 60, passes = 2;
uint64_t seed = 1;
OracleMode oracle = OracleMode::Cold;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string {
if (i + 1 >= argc) { usage(); std::exit(2); }
return argv[++i];
};
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 == "--oracle") {
const std::string m = next();
oracle = m == "all" ? OracleMode::All : m == "off" ? OracleMode::Off : OracleMode::Cold;
} else { usage(); return 2; }
}
if (tok_path.empty() || tpl_path.empty()) { usage(); return 2; }
if (cfg_path.empty()) {
const size_t slash = tok_path.find_last_of('/');
cfg_path = (slash == std::string::npos ? std::string() : tok_path.substr(0, slash + 1)) +
"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. */
rad::log_set_level(rad::Log::Warn);
std::setvbuf(stdout, nullptr, _IOLBF, 0);
/* The vocabulary, as the engine builds it. */
VocabBuild vb;
if (parse_tokenizer_json(tok_path.c_str(), vb) < 0) {
std::fprintf(stderr, "rad-gbnf-check: cannot read %s\n", tok_path.c_str());
return 2;
}
auto vocab = std::make_shared<Vocab>();
if (vocab->load(std::move(vb)) < 0) return 2;
RealView view;
if (view.init(vocab) < 0) return 2;
const double rss_vocab = rss_mib();
GbnfVocabInfo vi;
if (gbnf_prepare_vocab(&view, &vi) < 0) return 2;
std::printf("vocabulary: %d tokens, %zu end-of-generation; index built in %.0f ms, %.1f MiB "
"(resident set +%.1f MiB)\n", view.n_tokens(), vocab->eog().size(), vi.build_ms,
(double)vi.bytes / (1024.0 * 1024.0), rss_mib() - rss_vocab);
Run base;
base.view = &view;
base.oracle = oracle;
base.n_words = bitmask_words(view.n_tokens());
for (int32_t t = 0; t < view.n_tokens(); ++t) {
const std::string& p = view.token_piece(t);
if (!p.empty() && p.find_first_of("\"<>{}[],:\n") != std::string::npos)
base.structural.push_back(t);
}
/* The chat template's tool-call grammar, with parallel tool calls off and on. */
bool ok = false;
const std::string tpl = slurp(tpl_path, &ok);
if (!ok) {
std::fprintf(stderr, "rad-gbnf-check: cannot read %s\n", tpl_path.c_str());
return 2;
}
std::string bos, eos;
{
bool cok = false;
const std::string cfg = slurp(cfg_path, &cok);
if (cok) {
try {
const ojson c = ojson::parse(cfg);
auto tokstr = [&](const char* k) -> std::string {
if (!c.contains(k) || c[k].is_null()) return "";
return c[k].is_string() ? c[k].get<std::string>() : c[k].value("content", "");
};
bos = tokstr("bos_token");
eos = tokstr("eos_token");
} catch (const std::exception&) {}
}
}
ChatTemplate ct;
if (ct.load(tpl, bos, eos) < 0) {
std::fprintf(stderr, "rad-gbnf-check: the template does not load\n");
return 2;
}
Totals tot;
const ojson messages = ojson::array({
ojson{ { "role", "system" }, { "content", "You are a coding agent." } },
ojson{ { "role", "user" }, { "content", "Add sharding to the cache." } } });
for (int par = 0; par < 2; ++par) {
std::string grammar;
for (const char* choice : { "auto", "required" }) {
ChatOptions opt;
opt.parallel_tool_calls = par != 0;
opt.tool_choice = choice;
ChatPrompt cp;
if (ct.apply(messages, ojson::parse(kTools), opt, &cp) < 0) continue;
if (cp.grammar.empty()) continue;
grammar = cp.grammar;
break;
}
const std::string label =
std::string("tool calls, parallel_tool_calls=") + (par ? "true" : "false");
if (grammar.empty()) {
std::printf("\n== %s: the template produces no tool-call grammar\n", label.c_str());
continue;
}
run_grammar(base, tot, label, grammar, tool_call_texts(), passes, n_walks, n_steps, seed);
}
/* JSON schemas: the built-in set, then any given. */
auto run_schema = [&](const std::string& label, const std::string& schema,
const std::vector<std::string>& docs) {
std::string gbnf, err;
if (grammar_from_json_schema(schema, "root", &gbnf, &err) < 0) {
std::printf("\n== %s: the schema does not convert: %s\n", label.c_str(), err.c_str());
return;
}
run_grammar(base, tot, label, gbnf, docs, passes, n_walks, n_steps, seed);
};
for (const SchemaCase& sc : schema_cases())
run_schema(std::string("json schema ") + sc.name, sc.schema, sc.docs);
for (const std::string& f : schema_files) {
bool fok = false;
const std::string s = slurp(f, &fok);
if (fok) run_schema("json schema " + f, s, {});
}
for (const GbnfCase& gc : gbnf_cases())
run_grammar(base, tot, "gbnf " + gc.name, gc.text, gc.docs, passes, n_walks, n_steps, seed);
for (const std::string& f : gbnf_files) {
bool fok = false;
const std::string s = slurp(f, &fok);
if (fok) run_grammar(base, tot, "gbnf " + f, s, {}, passes, n_walks, n_steps, seed);
}
std::printf("\n== all grammars\n");
std::printf(" masks computed: %s\n", tot.cold.line().c_str());
if (!tot.cold_split.v.empty())
std::printf(" ... at a split character: %s\n", tot.cold_split.line().c_str());
std::printf(" masks from cache: %s\n", tot.warm.line().c_str());
std::printf(" replay steps, cold program: %.3f ms mean, %s\n", tot.first_steps.mean(),
tot.first_steps.line().c_str());
if (oracle != OracleMode::Off)
std::printf(" oracle: %lld states compared, %lld mismatches\n", (long long)tot.compared,
(long long)tot.mismatches);
std::printf(" resident set %.1f MiB\n", rss_mib());
return tot.mismatches ? 1 : 0;
}
+459
View File
@@ -0,0 +1,459 @@
/* 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.
*
* `--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.
*/
#include "iface.h"
#include "format/encoding.h"
#include <algorithm>
#include <cinttypes>
#include <cstdio>
#include <cstring>
#include <map>
using namespace rad;
namespace {
void usage() {
std::printf(
"rad-info -- print what a .rad container holds\n"
"\n"
"usage: rad-info [options] <model.rad>\n"
" rad-info --plugins [--home DIRS]\n"
"\n"
" -v, --verbose list every tensor, not just the per-unit summary\n"
" --meta print the metadata table and stop\n"
" --vocab print the vocab summary and its normaliser chain, and stop\n"
" --profile N print the top N entries of the expert profile (default 20, 0 = all)\n"
" --recipe print the recipe the container was converted with, and stop\n"
" --plugins print every plugin the $RADIANCE_HOME search path offers, as the\n"
" engine loads it, and stop\n"
" --home DIRS the search path for --plugins (default $RADIANCE_HOME)\n"
" -h, --help\n");
}
std::string shape_str(const int64_t* shape, uint32_t rank) {
if (rank == 0) return "-";
std::string s;
for (uint32_t i = 0; i < rank; ++i) {
if (i) s += 'x';
s += fmt("%lld", (long long)shape[i]);
}
return s;
}
const char* step_name(uint32_t k) {
switch (k) {
case RAD_NORM_NFC: return "norm.NFC";
case RAD_NORM_NFKC: return "norm.NFKC";
case RAD_NORM_NFD: return "norm.NFD";
case RAD_NORM_NFKD: return "norm.NFKD";
case RAD_NORM_LOWERCASE: return "norm.Lowercase";
case RAD_NORM_STRIP: return "norm.Strip";
case RAD_NORM_REPLACE: return "norm.Replace";
case RAD_NORM_PREPEND: return "norm.Prepend";
case RAD_PRE_BYTELEVEL: return "pre.ByteLevel";
case RAD_PRE_SPLIT: return "pre.Split";
case RAD_PRE_METASPACE: return "pre.Metaspace";
case RAD_PRE_WHITESPACE: return "pre.Whitespace";
case RAD_PRE_PUNCTUATION: return "pre.Punctuation";
case RAD_PRE_DIGITS: return "pre.Digits";
case RAD_PRE_BYTE_FALLBACK: return "pre.ByteFallback";
case RAD_DEC_BYTELEVEL: return "dec.ByteLevel";
case RAD_DEC_METASPACE: return "dec.Metaspace";
case RAD_DEC_REPLACE: return "dec.Replace";
case RAD_DEC_STRIP: return "dec.Strip";
case RAD_DEC_FUSE: return "dec.Fuse";
case RAD_DEC_BYTE_FALLBACK: return "dec.ByteFallback";
default: return "?";
}
}
const char* tok_kind(uint32_t k) {
switch (k) {
case RAD_TOK_BPE: return "bpe";
case RAD_TOK_UNIGRAM: return "unigram";
case RAD_TOK_WORDPIECE: return "wordpiece";
case RAD_TOK_RWKV: return "rwkv";
default: return "?";
}
}
/* 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. */
std::string vis(const char* s, size_t cap = 40) {
std::string out;
for (const char* p = s; *p && out.size() < cap; ++p) {
unsigned char c = (unsigned char)*p;
if (c == '\n') out += "\\n";
else if (c == '\t') out += "\\t";
else if (c < 0x20) out += fmt("\\x%02x", c);
else out.push_back((char)c);
}
if (out.size() >= cap) out += "...";
return out;
}
/* ------------------------------------------------------------------ sections */
void print_header(const RadFile& f) {
const RadFileHeader& h = f.header();
std::printf("%s\n", f.path());
std::printf(" format RAD%u, %s, little-endian\n", h.version,
humanb((int64_t)h.file_bytes).c_str());
std::printf(" architecture %s\n", f.str(h.arch_id));
std::printf(" model %s\n", f.str(h.model_name));
std::printf(" source quant %s\n", f.str(h.quant)[0] ? f.str(h.quant) : "(none)");
{
const char* r = f.str(h.recipe);
int lines = 0;
for (const char* p = r; *p; ++p) lines += *p == '\n';
if (r[0] && r[std::strlen(r) - 1] != '\n') ++lines;
std::printf(" recipe %s\n",
r[0] ? fmt("%d line(s) -- --recipe prints it", lines).c_str()
: "(none: every weight is the checkpoint's own)");
}
std::printf(" created by %s\n", f.str(h.created_by));
std::printf("\n section offset bytes count\n");
auto row = [&](const char* n, uint64_t off, uint64_t bytes, const char* count) {
std::printf(" %-12s %9llu %12s %8s\n", n, (unsigned long long)off,
humanb((int64_t)bytes).c_str(), count);
};
row("strings", h.str_off, h.str_bytes, "-");
row("metadata", h.meta_off, h.meta_count * sizeof(RadFileKV),
fmt("%llu", (unsigned long long)h.meta_count).c_str());
row("directory",h.dir_off, h.dir_count * sizeof(RadFileEntry),
fmt("%llu", (unsigned long long)h.dir_count).c_str());
row("planes", h.plane_off, h.plane_count * sizeof(RadFilePlane),
fmt("%llu", (unsigned long long)h.plane_count).c_str());
row("encodings",h.enc_off, h.enc_count * sizeof(RadEncoding),
fmt("%llu", (unsigned long long)h.enc_count).c_str());
row("vocab", h.vocab_off, h.vocab_bytes, "-");
row("profile", h.prof_off, h.prof_count * sizeof(RadFileProfile),
fmt("%llu", (unsigned long long)h.prof_count).c_str());
row("data", h.data_off, h.data_bytes,
fmt("%llu", (unsigned long long)h.dir_count).c_str());
}
void print_meta(const RadFile& f) {
if (f.meta_count() == 0) { std::printf("\nmetadata: none\n"); return; }
std::printf("\nmetadata (%lld)\n", (long long)f.meta_count());
size_t w = 4;
for (int64_t i = 0; i < f.meta_count(); ++i)
w = std::max(w, std::strlen(f.str(f.meta_at(i).key)));
w = std::min<size_t>(w, 44);
for (int64_t i = 0; i < f.meta_count(); ++i) {
const RadFileKV& kv = f.meta_at(i);
std::printf(" %-*s ", (int)w, f.str(kv.key));
switch (kv.type) {
case RAD_P_INT: std::printf("%lld\n", (long long)kv.v.i); break;
case RAD_KV_F64: std::printf("%g\n", kv.v.f); break;
case RAD_P_STR: std::printf("%s\n", vis(f.str(kv.v.s), 120).c_str()); break;
default: std::printf("(type %u)\n", kv.type); break;
}
}
}
/* Where a weight's numbers came from: the checkpoint as it was, or a quantiser and its options. */
std::string provenance(const RadFile& f, const RadFileEntry& e) {
const char* q = f.str(e.quantizer);
if (!q[0]) return "checkpoint";
const char* o = f.str(e.options);
return o[0] ? fmt("%s %s", q, o) : std::string(q);
}
void print_tensor_row(const RadFile& f, const RadFileEntry& e, const char* indent) {
std::printf("%s%-44s %-30s %-16s %12s @%-12llu %s\n", indent, f.str(e.name),
enc_name(f.encoding(e)).c_str(), shape_str(e.shape, e.rank).c_str(),
humanb((int64_t)e.bytes).c_str(), (unsigned long long)e.offset,
provenance(f, e).c_str());
const RadEncoding& enc = f.encoding(e);
if (e.n_planes > 1)
for (uint32_t k = 0; k < e.n_planes; ++k) {
const RadFilePlane& p = f.plane(e, (int)k);
std::printf("%s plane %-12s %-9s %12s @%llu\n", indent, enc.plane[k].role,
rad_dtype_name(enc.plane[k].dtype), humanb((int64_t)p.bytes).c_str(),
(unsigned long long)p.offset);
}
}
/* 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. */
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());
if (f.entry_count() == 0) return;
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. */
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;
for (int64_t k = 0; k < f.entry_count(); ++k) {
const RadFileEntry& e = f.entry(k);
for (uint32_t p = 0; p < e.n_planes; ++p) total_payload += (int64_t)f.plane(e, (int)p).bytes;
auto& a = by_enc[enc_name(f.encoding(e))];
++a.first; a.second += (int64_t)e.bytes;
auto& b = by_prov[provenance(f, e)];
++b.first; b.second += (int64_t)e.bytes;
}
while (i < f.entry_count()) {
const int32_t layer = f.entry(i).layer;
/* Non-expert entries of this layer. */
int64_t j = i;
int64_t unit_bytes = 0, n = 0;
while (j < f.entry_count() && f.entry(j).layer == layer && f.entry(j).expert < 0) {
unit_bytes += (int64_t)f.entry(j).bytes;
++j; ++n;
}
if (n) {
std::printf("\n %-20s %3lld tensor(s) %14s unit: one tensor\n",
rad_unit_name(layer, -1).c_str(), (long long)n,
humanb(unit_bytes).c_str());
if (verbose) for (int64_t k = i; k < j; ++k) print_tensor_row(f, f.entry(k), " ");
}
i = j;
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 */
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. */
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(),
humanb((int64_t)(g->stride - g->unit_bytes)).c_str());
for (int32_t s = 0; s < g->n_slot; ++s) {
const RadFileEntry& e = f.expert_entry(*g, 0, s);
std::printf(" slot %d +%-10llu %-40s %-30s %-16s %10s\n", s,
(unsigned long long)g->slot_off[s], f.str(e.name),
enc_name(f.encoding(e)).c_str(), shape_str(e.shape, e.rank).c_str(),
humanb((int64_t)e.bytes).c_str());
}
if (verbose)
for (int32_t e_id = 0; e_id < g->n_expert; ++e_id)
for (int32_t s = 0; s < g->n_slot; ++s)
print_tensor_row(f, f.expert_entry(*g, e_id, s), " ");
i = g->first_index + (int64_t)g->n_expert * g->n_slot;
}
const int64_t blob = (int64_t)f.header().data_bytes;
std::printf("\n pool totals\n");
std::printf(" planes %14s\n", humanb(total_payload).c_str());
std::printf(" alignment pad %14s (%u B per entry, %u B per plane; the movement unit\n"
" never straddles a page needlessly)\n",
humanb(blob - total_payload).c_str(), RAD_ALIGN_UNIT, RAD_ALIGN_SUB);
std::printf(" data blob %14s\n", humanb(blob).c_str());
auto table = [&](const char* title, const std::map<std::string, std::pair<int64_t, int64_t>>& m) {
std::printf("\n %s\n", title);
std::vector<std::pair<std::string, std::pair<int64_t, int64_t>>> v(m.begin(), m.end());
std::sort(v.begin(), v.end(), [](const auto& a, const auto& b) {
return a.second.second > b.second.second;
});
for (auto& [k, c] : v)
std::printf(" %-40s %7lld %14s %5.1f%%\n", k.c_str(), (long long)c.first,
humanb(c.second).c_str(),
blob ? 100.0 * (double)c.second / (double)blob : 0.0);
};
table("by encoding", by_enc);
table("by what made it", by_prov);
}
void print_vocab(const RadFile& f) {
VocabSection v = f.vocab();
if (!v) { std::printf("\nvocab: none baked into this container\n"); return; }
std::printf("\nvocab\n");
std::printf(" kind %s\n", tok_kind(v.h->kind));
std::printf(" tokens %u\n", v.h->n_tokens);
std::printf(" merges %u\n", v.h->n_merges);
std::printf(" specials bos=%d eos=%d eot=%d pad=%d unk=%d sep=%d add_bos=%u add_eos=%u\n",
v.h->bos, v.h->eos, v.h->eot, v.h->pad_id, v.h->unk, v.h->sep,
v.h->add_bos, v.h->add_eos);
const char* ct = f.str(v.h->chat_template);
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. */
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];
std::printf(" %2u %-20s flags=0x%x", i, step_name(s.kind), s.flags);
if (f.str(s.arg0)[0]) std::printf(" arg0=\"%s\"", vis(f.str(s.arg0), 60).c_str());
if (f.str(s.arg1)[0]) std::printf(" arg1=\"%s\"", vis(f.str(s.arg1), 60).c_str());
if (s.iarg) std::printf(" i=%lld", (long long)s.iarg);
std::printf("\n");
}
} else {
std::printf(" chain EMPTY -- nothing will split the input. If this came from a\n"
" tokenizer.json the converter did not interpret it.\n");
}
if (v.tok_type) {
int64_t n[8] = {0};
for (uint32_t i = 0; i < v.h->n_tokens; ++i)
n[v.tok_type[i] < 8 ? v.tok_type[i] : 0]++;
std::printf(" token types normal=%lld unknown=%lld control=%lld user=%lld byte=%lld\n",
(long long)n[RAD_TT_NORMAL], (long long)n[RAD_TT_UNKNOWN],
(long long)n[RAD_TT_CONTROL], (long long)n[RAD_TT_USER_DEFINED],
(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. */
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) {
if (v.tok_type[i] != RAD_TT_CONTROL && v.tok_type[i] != RAD_TT_USER_DEFINED) continue;
const char* mark = (int32_t)i == v.h->eos ? " <- eos"
: (int32_t)i == v.h->eot ? " <- eot" : "";
std::printf(" %-8u %-8s \"%s\"%s\n", i,
v.tok_type[i] == RAD_TT_CONTROL ? "control" : "user",
vis(f.str(v.tok_text[i]), 40).c_str(), mark);
}
}
const uint32_t show = std::min<uint32_t>(v.h->n_tokens, 8);
if (show) {
std::printf(" first %u ", show);
for (uint32_t i = 0; i < show; ++i)
std::printf("%s\"%s\"", i ? " " : "", vis(f.str(v.tok_text[i]), 16).c_str());
std::printf("\n");
}
}
void print_profile(const RadFile& f, int top) {
if (f.profile_count() == 0) {
std::printf("\nexpert profile: none. The placement planner will start cold and the heat\n"
"engine will rank from real routing within a few dispatches (spec §5.3).\n");
return;
}
std::printf("\nexpert profile (%lld entries, from the imatrix's activation counts)\n",
(long long)f.profile_count());
std::printf(" This is a WARM START, not a policy: imatrix popularity is calibration-set\n"
" popularity, not decode popularity, and the heat engine replaces it within a\n"
" few hundred steps. What it buys is the first few hundred.\n");
std::vector<const RadFileProfile*> v;
v.reserve((size_t)f.profile_count());
for (int64_t i = 0; i < f.profile_count(); ++i) v.push_back(&f.profile()[i]);
std::sort(v.begin(), v.end(),
[](const RadFileProfile* a, const RadFileProfile* b) { return a->share > b->share; });
const int n = (top <= 0) ? (int)v.size() : std::min<int>(top, (int)v.size());
std::printf("\n rank layer expert share\n");
for (int i = 0; i < n; ++i)
std::printf(" %4d %5d %6d %7.4f%%\n", i + 1, v[i]->layer, v[i]->expert,
100.0 * v[i]->share);
if (n < (int)v.size())
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. */
int print_plugins(const std::string& home) {
LoadedPlugins lp;
if (rad_tools_load_plugins(home, rad_hierarchy_from_env(), "", "", &lp) < 0) return 1;
const Registry& reg = rad_tools_registry();
std::printf("plugins on %s\n", home.c_str());
for (const Plugin& p : reg.plugins()) {
std::string what;
if (p.kind == RAD_PLUGIN_KERNEL) {
what = fmt("kernels %4d kernel(s), %3d schema(s), built for %s%s%s", p.n_kernels,
p.n_schemas, p.build_target.empty() ? "anything" : p.build_target.c_str(),
p.reference ? ", a reference implementation" : "",
p.device_code_absent ? ", no device code for this card" : "");
} else if (p.kind == RAD_PLUGIN_ARCH) {
what = fmt("architecture %s @ %s", p.arch_id.c_str(),
p.arch_quant.empty() ? "(unquantised)" : p.arch_quant.c_str());
} else {
std::string names;
for (const auto& q : reg.quantizers())
if (q.plugin == p.name && q.info) names += (names.empty() ? "" : " ") + std::string(q.info->name);
what = "quantizers " + names;
}
std::printf(" %2d %-16s %-8s %s\n %s\n", p.order, p.name.c_str(), p.version.c_str(),
what.c_str(), p.path.c_str());
}
return 0;
}
} /* namespace */
int main(int argc, char** argv) {
std::string path;
bool verbose = false, only_meta = false, only_vocab = false, only_recipe = false, plugins = false;
std::string home = rad_home();
int top = 20;
for (int i = 1; i < argc; ++i) {
std::string a = argv[i];
auto next = [&](const char* what) -> const char* {
if (i + 1 >= argc) { std::fprintf(stderr, "rad-info: %s needs a value\n", what);
std::exit(2); }
return argv[++i];
};
if (a == "-h" || a == "--help") { usage(); return 0; }
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 == "--recipe") only_recipe = true;
else if (a == "--plugins") plugins = true;
else if (a == "--home") home = next("--home");
else if (!a.empty() && a[0] == '-') {
std::fprintf(stderr, "rad-info: unrecognised argument '%s'. Try --help.\n", a.c_str());
return 2;
} else if (path.empty()) path = a;
else { std::fprintf(stderr, "rad-info: more than one model given\n"); return 2; }
}
if (plugins) return print_plugins(home);
if (path.empty()) { usage(); return 2; }
RadFile f;
int s = f.open(path.c_str());
if (s < 0) return 1;
if (only_recipe) {
const char* r = f.str(f.header().recipe);
std::fputs(r[0] ? r : "# no recipe: every weight is the checkpoint's own\n", stdout);
return 0;
}
if (only_meta) { print_meta(f); return 0; }
if (only_vocab) { print_vocab(f); return 0; }
print_header(f);
print_meta(f);
print_directory(f, verbose);
print_vocab(f);
print_profile(f, top);
return 0;
}
+3114
View File
File diff suppressed because it is too large. Load diff
+151
View File
@@ -0,0 +1,151 @@
/* 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.
*
* rad-schemas libref.so print one plugin's vocabulary
* rad-schemas libr4d.so libref.so diff them, in hierarchy order
*/
#include "rad_abi.h"
#include <dlfcn.h>
#include <cstdio>
#include <cstring>
#include <map>
#include <set>
#include <string>
#include <vector>
namespace {
struct Loaded {
std::string name, path;
void* h = nullptr;
std::map<std::string, const RadOpSchema*> ops;
};
const char* ptype(int t) { return t == RAD_P_INT ? "int" : t == RAD_P_STR ? "str"
: t == RAD_P_F64 ? "f64" : "?"; }
const char* preq(int r) { return r == RAD_REQUIRED ? "required"
: r == RAD_DERIVED ? "derived" : "optional"; }
const char* orole(int r) { return r == RAD_OPD_IN ? "in" : r == RAD_OPD_OUT ? "out"
: r == RAD_OPD_INOUT ? "inout"
: r == RAD_OPD_WTAB ? "wtab" : "weight"; }
std::string params_of(const RadOpSchema* s) {
std::string o;
for (int i = 0; i < s->n_params; ++i) {
if (i) o += ' ';
o += s->params[i].key;
o += ':';
o += ptype(s->params[i].type);
if (s->params[i].required != RAD_REQUIRED) { o += '/'; o += preq(s->params[i].required); }
}
return o;
}
std::string operands_of(const RadOpSchema* s) {
std::string o;
for (int i = 0; i < s->n_operands; ++i) {
if (i) o += ' ';
o += s->operands[i].name;
o += ':';
o += orole(s->operands[i].role);
if (s->operands[i].optional) o += "?";
}
return o;
}
int load(const char* path, Loaded* out) {
out->path = path;
out->h = dlopen(path, RTLD_NOW | RTLD_LOCAL);
if (!out->h) { fprintf(stderr, "dlopen(%s): %s\n", path, dlerror()); return -1; }
auto abi = (uint32_t (*)(void))dlsym(out->h, "rad_plugin_abi_version");
auto inf = (const RadPluginInfo* (*)(void))dlsym(out->h, "rad_plugin_info");
auto cnt = (int (*)(void))dlsym(out->h, "rad_kernel_schema_count");
auto at = (const RadOpSchema* (*)(int))dlsym(out->h, "rad_kernel_schema_at");
if (!abi || !cnt || !at) { fprintf(stderr, "%s: not a kernel plugin\n", path); return -1; }
if (abi() != RAD_ABI_VERSION) {
fprintf(stderr, "%s: ABI %u, this build is %u\n", path, abi(), RAD_ABI_VERSION);
return -1;
}
out->name = inf && inf()->name ? inf()->name : path;
for (int i = 0, n = cnt(); i < n; ++i) {
const RadOpSchema* s = at(i);
if (s && s->op) out->ops[s->op] = s;
}
return 0;
}
} /* namespace */
int main(int argc, char** argv) {
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");
return 2;
}
std::vector<Loaded> pl((size_t)(argc - 1));
for (int i = 1; i < argc; ++i)
if (load(argv[i], &pl[(size_t)i - 1]) < 0) return 1;
if (pl.size() == 1) {
printf("%s -- %zu ops\n\n", pl[0].name.c_str(), pl[0].ops.size());
for (auto& [op, s] : pl[0].ops) {
printf(" %s\n", op.c_str());
printf(" params %s\n", params_of(s).c_str());
printf(" operands %s\n", operands_of(s).c_str());
}
return 0;
}
/* Every op anyone declares, and who declares it. */
std::set<std::string> all;
for (auto& p : pl) for (auto& [op, s] : p.ops) all.insert(op);
int conflicts = 0, shared = 0;
for (const std::string& op : all) {
std::vector<const Loaded*> have;
for (auto& p : pl) if (p.ops.count(op)) have.push_back(&p);
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);
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;
}
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());
}
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");
return conflicts ? 1 : 0;
}
+275
View File
@@ -0,0 +1,275 @@
/* rad-tokcheck -- hold the tokeniser to its references over real text, and time 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.
*
* Exits non-zero on any difference, so it can gate a change.
*/
#include "text/tokenizer.h"
#include "tokref.h"
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace rad;
namespace {
void usage() {
std::printf(
"rad-tokcheck -- compare the tokeniser against its reference encoder and HuggingFace\n"
"\n"
"usage: rad-tokcheck [options] <tokenizer.json> <corpus-file>...\n"
"\n"
" --hf-dir DIR compare against HuggingFace ids in DIR/<corpus basename>.ids\n"
" (little-endian int32, encode(text, add_special_tokens=False))\n"
" --no-ref skip the reference encoder, which is slow\n"
" --user encode with parse_special off, as the server does for user content\n"
" --turns N turns in the multi-turn measurement (default 40, 0 skips it)\n"
" --repeat N timing repeats, best taken (default 3)\n"
" --context N ids shown either side of a difference (default 6)\n"
" -h, --help\n");
}
using Clock = std::chrono::steady_clock;
double secs(Clock::time_point a) { return std::chrono::duration<double>(Clock::now() - a).count(); }
bool read_file(const std::string& path, std::string* out) {
std::ifstream f(path, std::ios::binary);
if (!f) return false;
std::ostringstream ss;
ss << f.rdbuf();
*out = ss.str();
return true;
}
std::string basename_of(const std::string& p) {
const size_t s = p.find_last_of('/');
return s == std::string::npos ? p : p.substr(s + 1);
}
std::string printable(const std::string& s) {
std::string o;
for (unsigned char c : s) {
if (c == '\n') o += "\\n";
else if (c == '\r') o += "\\r";
else if (c == '\t') o += "\\t";
else if (c < 0x20 || c == 0x7F) o += fmt("\\x%02x", c);
else o += (char)c;
}
return o;
}
/* The first index where `a` and `b` differ, printed with the ids either side and the text they
* spell. Returns false when they are identical. */
bool report_diff(const Tokenizer& tok, const char* what, const std::vector<int32_t>& a,
const std::vector<int32_t>& b, const std::string& text, int ctx) {
size_t i = 0;
while (i < a.size() && i < b.size() && a[i] == b[i]) ++i;
if (i == a.size() && i == b.size()) return false;
size_t byte = 0;
for (size_t k = 0; k < i; ++k) byte += tok.piece(a[k], true).size();
std::printf(" DIFFERENT from %s at id %zu (of %zu vs %zu), about byte %zu\n", what, i,
a.size(), b.size(), byte);
const size_t lo = i > (size_t)ctx ? i - ctx : 0;
auto show = [&](const char* name, const std::vector<int32_t>& v) {
std::printf(" %-9s", name);
for (size_t k = lo; k < std::min(v.size(), i + ctx); ++k)
std::printf("%s%d'%s'", k == i ? " >>" : " ", v[k], printable(tok.piece(v[k], true)).c_str());
std::printf("\n");
};
show("tokenizer", a);
show(what, b);
const size_t t0 = byte > 60 ? byte - 60 : 0;
std::printf(" text '%s'\n",
printable(text.substr(t0, std::min<size_t>(120, text.size() - std::min(t0, text.size())))).c_str());
return true;
}
/* The corpus cut into `n` turns at line boundaries, and each turn's prompt: every message so far,
* alternating user and assistant, framed the way a ChatML template frames them when the vocab has
* its markers. */
std::vector<std::string> conversation(const Vocab& v, const std::string& text, int n) {
std::vector<std::string> msgs;
const size_t per = text.size() / (size_t)n + 1;
size_t pos = 0;
while (pos < text.size() && (int)msgs.size() < n) {
size_t end = std::min(text.size(), pos + per);
const size_t nl = text.find('\n', end);
end = nl == std::string::npos ? text.size() : nl + 1;
msgs.push_back(text.substr(pos, end - pos));
pos = end;
}
const bool chatml = v.find("<|im_start|>") >= 0 && v.find("<|im_end|>") >= 0;
std::vector<std::string> prompts;
std::string conv;
for (size_t k = 0; k < msgs.size(); ++k) {
const char* role = k % 2 ? "assistant" : "user";
conv += chatml ? std::string("<|im_start|>") + role + "\n" + msgs[k] + "<|im_end|>\n" : msgs[k];
prompts.push_back(conv + (chatml ? "<|im_start|>assistant\n" : ""));
}
return prompts;
}
} /* namespace */
int main(int argc, char** argv) {
std::string hf_dir;
bool ref = true, parse_special = true;
int turns = 40, repeat = 3, ctx = 6;
std::vector<std::string> args;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> const char* {
if (i + 1 >= argc) { std::fprintf(stderr, "rad-tokcheck: %s needs a value\n", a.c_str()); std::exit(2); }
return argv[++i];
};
if (a == "-h" || a == "--help") { usage(); return 0; }
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.empty() && a[0] == '-') { std::fprintf(stderr, "rad-tokcheck: unknown option %s\n", a.c_str()); return 2; }
else args.push_back(a);
}
if (args.size() < 2) { usage(); return 2; }
log_set_level(Log::Warn);
VocabBuild vb;
if (parse_tokenizer_json(args[0].c_str(), vb) < 0) return 1;
auto vocab = std::make_shared<Vocab>();
const auto l0 = Clock::now();
if (vocab->load(std::move(vb)) < 0) return 1;
const double load_s = secs(l0);
Tokenizer tok;
if (tok.init(vocab) < 0) return 1;
tok.set_segment_cache(false);
std::printf("%s: %d tokens, vocab load %.1f ms\n", args[0].c_str(), vocab->n_tokens(), load_s * 1e3);
int bad = 0;
size_t total_bytes = 0;
double total_new = 0, total_ref = 0;
size_t total_ids = 0, hf_checked = 0;
for (size_t f = 1; f < args.size(); ++f) {
std::string text;
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. */
std::vector<int32_t> ids;
double best = 1e30, first = 0;
for (int r = 0; r < repeat; ++r) {
ids.clear();
const auto t0 = Clock::now();
if (tok.encode(text, ids, false, parse_special) < 0) { std::printf(" encode failed\n"); ++bad; break; }
const double t = secs(t0);
if (r == 0) first = t;
best = std::min(best, t);
}
std::printf(" tokenizer %8zu ids %8.2f ms %7.1f MB/s (first encode %.2f ms, %.1f MB/s)\n",
ids.size(), best * 1e3, text.size() / best / 1e6, first * 1e3,
text.size() / first / 1e6);
total_bytes += text.size();
total_new += best;
total_ids += ids.size();
if (ref) {
std::vector<int32_t> rids;
const auto t0 = Clock::now();
const int st = tokref::encode(*vocab, text, rids, false, parse_special);
const double rs = secs(t0);
if (st < 0) {
std::printf(" reference failed (%d)\n", st);
} else {
std::printf(" reference %8zu ids %8.2f ms %7.1f MB/s\n", rids.size(), rs * 1e3,
text.size() / rs / 1e6);
total_ref += rs;
if (report_diff(tok, "reference", ids, rids, text, ctx)) ++bad;
else std::printf(" reference identical\n");
}
}
if (!hf_dir.empty()) {
std::string raw;
const std::string path = hf_dir + "/" + basename_of(args[f]) + ".ids";
if (!read_file(path, &raw)) {
std::printf(" huggingface: no %s\n", path.c_str());
} else {
std::vector<int32_t> hids(raw.size() / 4);
std::memcpy(hids.data(), raw.data(), hids.size() * 4);
++hf_checked;
if (report_diff(tok, "hf", ids, hids, text, ctx)) ++bad;
else std::printf(" huggingface identical (%zu ids)\n", hids.size());
}
}
if (turns > 0) {
const std::vector<std::string> prompts = conversation(*vocab, text, turns);
Tokenizer cached;
cached.init(vocab);
cached.clear_cache();
double cold = 0, warm = 0, cold_last = 0, warm_last = 0, rtot = 0, rlast = 0;
size_t prompt_bytes = 0;
bool same = true;
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 double c = secs(t0);
t0 = Clock::now();
cached.encode(prompts[k], b, false, true);
const double w = secs(t0);
cold += c;
warm += w;
cold_last = c;
warm_last = w;
prompt_bytes += prompts[k].size();
if (a != b) {
same = false;
report_diff(tok, "cached", a, b, prompts[k], ctx);
}
if (ref) {
t0 = Clock::now();
tokref::encode(*vocab, prompts[k], r, false, true);
rlast = secs(t0);
rtot += rlast;
}
}
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");
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);
if (ref)
std::printf(" reference %9.1f ms total, last turn %8.2f ms\n", rtot * 1e3, rlast * 1e3);
if (!same) ++bad;
}
}
std::printf("total: %.1f MB, %zu ids; tokenizer %.1f MB/s", total_bytes / 1e6, total_ids,
total_bytes / total_new / 1e6);
if (ref && total_ref > 0) std::printf(", reference %.1f MB/s", total_bytes / total_ref / 1e6);
if (!hf_dir.empty()) std::printf("; %zu file(s) checked against huggingface", hf_checked);
std::printf("; %d difference(s)\n", bad);
return bad ? 1 : 0;
}
+648
View File
@@ -0,0 +1,648 @@
/* 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.
*
* 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.
*
* 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.
*
* 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.
*/
#include "kfixture.h"
#include "opshapes.h"
#include "format/tunecache.h"
#include "rad_device.h"
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <map>
#include <thread>
#include <vector>
using namespace rad;
namespace {
void usage() {
std::printf(
"rad-tune -- benchmark each kernel's tunable space at this model's shapes, on this machine\n"
"\n"
"usage: rad-tune -m <model.rad> [options]\n"
"\n"
" -m, --model FILE the .rad whose declared graph supplies the shapes\n"
" --home DIR $RADIANCE_HOME; the cache is written to <home>/tune/<machine>.tune\n"
" --kernels A:B kernel plugin hierarchy, first wins\n"
" --op NAME tune only ops whose name starts with NAME\n"
" --machine KEY override the machine key (for writing a cache for another box)\n"
" --reps N timing reps, median reported (default 5)\n"
" --iters N launches per rep (default 32). One launch is short enough that\n"
" launch overhead and clock ramp would otherwise dominate.\n"
" --max-tok N the max_tok declare is run at (default 8192)\n"
" --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"
" --dry-run list what would be measured and stop\n"
" -v, --verbose print every candidate, not just the winner\n"
" -h, --help\n");
}
/* A device allocation that frees itself, because the timing path has several ways out. */
struct DevBuf {
void* p = nullptr;
~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. */
constexpr double kVariantTol = 1e-3;
/* THE CANDIDATES: every legal point in the kernel's declared space, at THIS geometry.
*
* 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.
*/
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) {
std::vector<std::vector<std::pair<std::string, int64_t>>> out;
if (!k || k->n_tunables <= 0) return out;
int64_t total = 1;
for (int i = 0; i < k->n_tunables; ++i) total *= (int64_t)k->tunables[i].n_values;
if (space_size) *space_size = total;
if (total <= 0 || total > (int64_t)kMaxCandidates) return out;
std::vector<RadParam> cp((size_t)k->n_tunables);
std::vector<int> idx((size_t)k->n_tunables, 0);
std::vector<std::pair<std::string, int64_t>> point((size_t)k->n_tunables);
for (int64_t n = 0; n < total; ++n) {
int64_t rem = n;
for (int i = k->n_tunables - 1; i >= 0; --i) {
idx[(size_t)i] = (int)(rem % k->tunables[i].n_values);
rem /= k->tunables[i].n_values;
}
for (int i = 0; i < k->n_tunables; ++i) {
point[(size_t)i].first = k->tunables[i].key;
point[(size_t)i].second = k->tunables[i].values[idx[(size_t)i]];
cp[(size_t)i].key = k->tunables[i].key;
cp[(size_t)i].kind = RAD_P_INT;
cp[(size_t)i].ival = point[(size_t)i].second;
}
if (k->tune_valid &&
k->tune_valid(g.params(), g.n_params(), cp.data(), (int)cp.size()) != 1) continue;
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. */
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; }
}
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. */
int capture_outputs(const KernelRow& row, std::vector<RadTensor>& t,
const Geometry& g, const RadOpSchema* schema,
const std::vector<OpdShape>& sh, RadStream stream,
std::vector<uint8_t>* out) {
RadArgs a{};
a.t = t.data(); a.n_t = (int)t.size();
a.p = g.params(); a.n_p = g.n_params();
a.rank = 0; a.world_size = 1;
DevBuf scratch;
if (row.info->scratch) {
const int64_t need = row.info->scratch(&a);
if (need > 0) {
scratch.p = rad_dev_alloc(need, RAD_MEM_DEVICE);
if (!scratch.p) return RAD_E_NOMEM;
rad_memset_async(scratch.p, 0, need, stream);
a.scratch = scratch.p;
a.scratch_bytes = need;
}
}
if (row.info->launch(&a, stream) < 0) return RAD_E_SHAPE;
if (stream && rad_stream_sync(stream) < 0) return RAD_E_STATE;
/* 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_t total = 0;
for (size_t k = 0; k < sh.size() && k < (size_t)schema->n_operands; ++k) {
const int role = schema->operands[k].role;
if (role != RAD_OPD_OUT && role != RAD_OPD_INOUT) continue;
if (!t[k].data) continue;
const int64_t bytes = rad_dtype_bytes(sh[k].dtype, rad_numel(sh[k].shape));
if (bytes > 0) total += (size_t)bytes;
}
out->assign(total, 0);
size_t at = 0;
for (size_t k = 0; k < sh.size() && k < (size_t)schema->n_operands; ++k) {
const int role = schema->operands[k].role;
if (role != RAD_OPD_OUT && role != RAD_OPD_INOUT) continue;
if (!t[k].data) continue;
const int64_t bytes = rad_dtype_bytes(sh[k].dtype, rad_numel(sh[k].shape));
if (bytes <= 0) continue;
if (rad_memcpy_async(out->data() + at, t[k].data, bytes, stream) < 0) return RAD_E_STATE;
at += (size_t)bytes;
}
if (stream && rad_stream_sync(stream) < 0) return RAD_E_STATE;
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. */
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;
double worst = 0.0;
size_t at = 0;
for (size_t k = 0; k < sh.size() && k < (size_t)schema->n_operands; ++k) {
const int role = schema->operands[k].role;
if (role != RAD_OPD_OUT && role != RAD_OPD_INOUT) continue;
const int64_t n = rad_numel(sh[k].shape);
const int64_t bytes = rad_dtype_bytes(sh[k].dtype, n);
if (bytes <= 0 || at + (size_t)bytes > a.size()) break;
std::vector<float> fa, fb;
rad_widen(a.data() + at, sh[k].dtype, n, &fa);
rad_widen(b.data() + at, sh[k].dtype, n, &fb);
if ((int64_t)fa.size() < n || (int64_t)fb.size() < n) break;
double num = 0, den = 0;
for (int64_t i = 0; i < n; ++i) {
const double d = (double)fa[(size_t)i] - (double)fb[(size_t)i];
num += d * d;
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. */
if (std::isnan(rel)) return rel;
if (rel > worst) worst = rel;
at += (size_t)bytes;
}
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. */
double time_point(const KernelRow& row, std::vector<RadTensor>& t,
const Geometry& g, int reps, int iters,
RadStream stream, double* spread_pct) {
RadArgs a{};
a.t = t.data(); a.n_t = (int)t.size();
a.p = g.params(); a.n_p = g.n_params();
a.rank = 0; a.world_size = 1;
/* 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. */
DevBuf scratch;
if (row.info->scratch) {
const int64_t need = row.info->scratch(&a);
if (need > 0) {
scratch.p = rad_dev_alloc(need, RAD_MEM_DEVICE);
if (!scratch.p) return (double)RAD_E_NOMEM;
rad_memset_async(scratch.p, 0, need, stream);
a.scratch = scratch.p;
a.scratch_bytes = need;
}
}
/* 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. */
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. */
std::vector<double> us;
us.reserve((size_t)reps);
for (int r = 0; r < reps; ++r) {
const auto t0 = std::chrono::steady_clock::now();
for (int i = 0; i < iters; ++i)
if (row.info->launch(&a, stream) < 0) return (double)RAD_E_SHAPE;
if (stream && rad_stream_sync(stream) < 0) return (double)RAD_E_STATE;
const auto t1 = std::chrono::steady_clock::now();
us.push_back(std::chrono::duration<double, std::micro>(t1 - t0).count() / iters);
}
std::sort(us.begin(), us.end());
if (spread_pct)
*spread_pct = us[us.size() / 2] > 0
? 100.0 * (us.back() - us.front()) / us[us.size() / 2] : 0.0;
return us[us.size() / 2];
}
} /* namespace */
int main(int argc, char** argv) {
std::string model, home = rad_home(), op_filter, machine;
std::vector<std::string> hierarchy = rad_hierarchy_from_env();
int reps = 5, iters = 32;
int64_t max_tok = 8192;
int tp = 1, spec = -1; /* -1 = the container's own drafter depth */
bool dry = false, verbose = false;
for (int i = 1; i < argc; ++i) {
std::string a = argv[i];
auto next = [&](const char* w) -> const char* {
if (i + 1 >= argc) { std::fprintf(stderr, "rad-tune: %s needs a value\n", w);
std::exit(2); }
return argv[++i];
};
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 == "--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;
LoadedPlugins plugins;
if (rad_tools_load_plugins(home, hierarchy, f.str(f.header().arch_id),
f.str(f.header().quant), &plugins) < 0) return 1;
RadModelMeta meta{};
meta.arch_id = f.str(f.header().arch_id);
meta.name = f.str(f.header().model_name);
meta.quant = f.str(f.header().quant);
auto mi = [&](const char* k, int64_t d) { int64_t v = d; f.get_i(k, &v); return v; };
auto mf = [&](const char* k, double d) { double v = d; f.get_f(k, &v); return (float)v; };
meta.n_layers = mi("n_layers", 0); meta.n_embd = mi("n_embd", 0);
meta.n_head = mi("n_head", 0); meta.n_head_kv = mi("n_head_kv", 0);
meta.head_dim = mi("head_dim", 0); meta.n_ff = mi("n_ff", 0);
meta.n_vocab = mi("n_vocab", 0); meta.n_ctx_train = mi("n_ctx_train", 0);
meta.n_expert = mi("n_expert", 0); meta.n_expert_used = mi("n_expert_used", 0);
meta.n_expert_shared = mi("n_expert_shared", 0);
meta.rms_eps = mf("rms_eps", 1e-6); meta.rope_theta = mf("rope_theta", 10000.f);
meta.rope_scale = mf("rope_scale", 1.f);
std::vector<std::string> kk, kv;
std::vector<const char*> kp, vp;
for (int64_t i = 0; i < f.meta_count(); ++i) {
const RadFileKV& e = f.meta_at(i);
if (e.type != RAD_P_STR) continue;
kk.push_back(f.str(e.key));
kv.push_back(f.str(e.v.s));
}
for (auto& s : kk) kp.push_back(s.c_str());
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. */
RadBuildCtx ctx{};
ctx.rank = 0; ctx.world_size = tp; ctx.max_tok = max_tok;
RadArchProbe probe{};
(void)rad_tools_probe(plugins, meta, &probe);
ctx.max_spec = spec >= 0 ? spec : probe.draft_depth;
ctx.max_seqs = 256; ctx.max_ctx = meta.n_ctx_train; ctx.scope = "";
/* 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. */
Program prog;
{
std::vector<Program> progs((size_t)tp);
std::vector<int> st((size_t)tp, 0);
std::vector<std::thread> th;
for (int ri = 0; ri < tp; ++ri) {
th.emplace_back([&, ri] {
if (tp > 1 && rad_dev_set(ri) < 0) {
std::fprintf(stderr, "rad-tune: --tp %d needs %d devices; there is no device "
"%d to declare rank %d on\n", tp, tp, ri, ri);
st[(size_t)ri] = RAD_E_DEVICE;
return;
}
RadBuildCtx bc = ctx;
bc.rank = ri;
st[(size_t)ri] = rad_tools_declare(plugins, meta, bc, &progs[(size_t)ri], {},
nullptr, rad_container_sources(f));
});
}
for (auto& t : th) t.join();
if (tp > 1) rad_dev_set(0);
for (int ri = 0; ri < tp; ++ri) if (st[(size_t)ri] < 0) return 1;
prog = std::move(progs[0]);
}
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. */
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();
TuneCache cache;
cache.load(src.substr(0, src.size() - rel.size() - 1), machine); /* missing is normal */
const size_t before = cache.rows().size();
std::printf("rad-tune %s\n", model.c_str());
std::printf(" machine %s\n", machine.c_str());
std::printf(" cache %s (%zu existing row(s))\n", src.c_str(), before);
std::printf(" requests %zu (kernel, shape) pair(s) the declared graph reaches\n\n",
prog.tune_requests.size());
Registry& reg = rad_tools_registry();
auto row_for = [&](const std::string& plugin, const std::string& kernel) -> const KernelRow* {
for (const KernelRow& r : reg.rows())
if (r.plugin == plugin && r.info && kernel == r.info->name) return &r;
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. */
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. */
RadStream stream = nullptr;
if (rad_stream_create(&stream, 0) < 0) {
std::fprintf(stderr, "rad-tune: could not create a stream: %s\n", rad_dev_last_error());
return 1;
}
for (const Program::TuneRequest& tr : prog.tune_requests) {
const KernelRow* row = row_for(tr.plugin, tr.kernel);
if (!row || !row->info || !row->info->launch) {
skip_why[tr.plugin + "/" + tr.kernel + " (no such kernel row)"]++;
++skipped;
continue;
}
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. */
int64_t space = 0;
const auto cands = tune_candidates(row->info, tr.geom, &space);
const int n_var = (int)cands.size();
if (n_var <= 1) { ++single; continue; }
const RadOpSchema* schema = reg.schema(op);
if (!schema) { skip_why[op + " (no schema)"]++; ++skipped; continue; }
int64_t M = 1;
long long mv = 0;
for (const char* k : { "M", "q_len" }) if (tr.geom.get_i(k, &mv)) { M = (int64_t)mv; break; }
if (M <= 0) M = 1;
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)"]++;
++skipped;
continue;
}
if (dry) {
std::printf(" %-22s %-46s %s/%s %d of %lld point(s)\n", op.c_str(),
tr.geom.str().c_str(), tr.plugin.c_str(), tr.kernel.c_str(), n_var,
(long long)space);
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. */
std::vector<KfOperand> kop(sh.size());
for (size_t k = 0; k < sh.size(); ++k) {
KfOperand& d = kop[k];
d.role = k < (size_t)schema->n_operands ? schema->operands[k].role : RAD_OPD_IN;
d.dtype = sh[k].dtype;
d.shape = sh[k].shape;
d.absent = sh[k].absent;
d.fill = sh[k].fill;
d.is_index = sh[k].is_index;
d.idx_unique = sh[k].idx_unique;
d.idx_cu = sh[k].idx_cu;
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. */
std::vector<std::vector<uint8_t>> store(sh.size());
std::vector<DevBuf> dev(sh.size());
std::vector<RadTensor> t(sh.size());
bool ok = true;
for (size_t k = 0; k < sh.size() && ok; ++k) {
const int64_t n = rad_numel(sh[k].shape);
const int64_t bytes = rad_dtype_bytes(sh[k].dtype, n);
if (bytes <= 0) { ok = false; break; }
kf_draw(kop, k, M, vocab_rows, rad_case_seed(1, op, 0, row->info->domain, (int)k),
&store[k]);
dev[k].p = rad_dev_alloc(bytes, RAD_MEM_DEVICE);
if (!dev[k].p) { ok = false; break; }
if (rad_memcpy_async(dev[k].p, store[k].data(), bytes, stream) < 0) { ok = false; break; }
t[k].data = dev[k].p;
t[k].dtype = sh[k].dtype;
t[k].rank = (uint32_t)sh[k].shape.size();
for (size_t d = 0; d < sh[k].shape.size() && d < RAD_MAX_RANK; ++d)
t[k].shape[d] = sh[k].shape[d];
rad_tensor_pack(&t[k]);
}
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. */
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. */
std::vector<double> best_us((size_t)n_var, -1.0), spread((size_t)n_var, 0.0);
for (int v = 0; v < n_var; ++v) {
double sp = 0;
best_us[(size_t)v] = time_point(*row, t, gv[(size_t)v], reps, iters, stream, &sp);
spread[(size_t)v] = sp;
}
/* ---- AND EACH ONE HAS TO 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. */
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[(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;
}
int win = -1;
for (int v = 0; v < n_var; ++v)
if (best_us[(size_t)v] > 0 && (win < 0 || best_us[(size_t)v] < best_us[(size_t)win]))
win = v;
if (win < 0) {
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;
continue;
}
const std::string wname = TuneCache::canon_choice(cands[(size_t)win]);
if (verbose)
for (int v = 0; v < n_var; ++v) {
const std::string nm = TuneCache::canon_choice(cands[(size_t)v]);
if (best_us[(size_t)v] > 0)
std::printf(" %-32s %9.3f us spread %4.0f%% vs default %8.2g%s\n",
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",
nm.c_str(), verr[(size_t)v]);
else
std::printf(" %-32s refused: %s\n", nm.c_str(),
rad_strerror((int)best_us[(size_t)v]));
}
TuneRow tr_out;
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. */
tr_out.geom = tr.geom_key;
tr_out.us = best_us[(size_t)win];
tr_out.measured = TuneCache::now_iso8601();
cache.put(tr_out);
++measured;
std::printf(" %-22s %-46s %-28s %9.3f us (%d of %lld)\n", op.c_str(),
tr.geom.str().c_str(), wname.c_str(), tr_out.us, n_var, (long long)space);
}
if (dry) {
std::printf("\n--dry-run: nothing measured, nothing written.\n");
return 0;
}
if (!skip_why.empty()) {
std::printf("\nskipped\n");
for (const auto& [what, n] : skip_why) std::printf(" %-70s x%d\n", what.c_str(), n);
std::printf(" %d request(s) skipped in total.\n", skipped);
}
if (single)
std::printf("\n%d request(s) had one point or none: nothing to choose, and the kernel's\n"
"own axis defaults are already what it runs.\n", single);
rad_stream_destroy(stream);
cache.set_machine(machine);
if (cache.save(save_home) < 0) return 1;
std::printf("\n%d shape(s) measured, %zu row(s) in %s\n", measured, cache.rows().size(),
TuneCache::path_for(save_home, machine).c_str());
return 0;
}
+702
View File
@@ -0,0 +1,702 @@
/* 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.
*/
#include "tokref.h"
#include "text/unicode_norm.h"
#include "llama/src/unicode.h"
#include <algorithm>
#include <cfloat>
#include <cstring>
#include <queue>
#include <regex>
namespace rad {
namespace tokref {
namespace {
struct ByteLevelAlphabet {
std::string to_utf8[256]; /* byte -> its 1-2 byte UTF-8 spelling */
std::unordered_map<std::string, uint8_t> from; /* and back */
uint32_t cpt_of[256];
ByteLevelAlphabet() {
bool taken[256] = { false };
auto give = [&](int b, uint32_t cpt) {
to_utf8[b] = unicode_cpt_to_utf8(cpt);
cpt_of[b] = cpt;
from[to_utf8[b]] = (uint8_t)b;
taken[b] = true;
};
for (int b = 0x21; b <= 0x7E; ++b) give(b, (uint32_t)b); /* '!' .. '~' */
for (int b = 0xA1; b <= 0xAC; ++b) give(b, (uint32_t)b); /* U+00A1..AC */
for (int b = 0xAE; b <= 0xFF; ++b) give(b, (uint32_t)b); /* U+00AE..FF */
uint32_t n = 0;
for (int b = 0; b < 256; ++b) if (!taken[b]) give(b, 256 + n++);
}
};
const ByteLevelAlphabet& alphabet() {
static const ByteLevelAlphabet a;
return a;
}
std::string byte_encode(std::string_view raw) {
const ByteLevelAlphabet& a = alphabet();
std::string out;
out.reserve(raw.size() * 2);
for (unsigned char c : raw) out += a.to_utf8[c];
return out;
}
constexpr const char* k_metaspace = "\xe2\x96\x81"; /* U+2581 LOWER ONE EIGHTH BLOCK */
void replace_all(std::string& s, std::string_view from, std::string_view to) {
if (from.empty()) return;
std::string out;
out.reserve(s.size());
size_t i = 0;
for (;;) {
size_t j = s.find(from, i);
if (j == std::string::npos) { out.append(s, i, std::string::npos); break; }
out.append(s, i, j - i);
out.append(to);
i = j + from.size();
}
s.swap(out);
}
/* ================================================================== the pre-tokeniser regex
*
* WHICH PATTERNS ARE HANDLED STRUCTURALLY AND WHICH FALL THROUGH -- read this before changing
* anything below it.
*
* 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:
* - 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;
* - 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.
*
* 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. */
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])";
std::string canonicalise_pattern(const std::string& p) {
std::string out = p;
replace_all(out, k_ci_contractions_in, k_ci_contractions_out);
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. */
bool pattern_is_structural(const std::string& raw) {
const std::string p = canonicalise_pattern(raw);
static const char* k_structural[] = {
"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
"\\p{Han}+",
"\\p{AFMoE_digits}",
"[^\\n]+|[\\n]+",
"\\d{1,3}(?=(?:\\d{3})*\\b)",
};
for (const char* s : k_structural) if (p == s) return true;
return false;
}
/* --- 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. */
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. */
RAD_WARN("tokenizer: Replace pattern '%s' did not compile (%s); step skipped",
s.arg0.c_str(), e.what());
}
} else {
replace_all(text, s.arg0, s.arg1);
}
}
void apply_norm(std::string& text, const VocabStep& s) {
switch (s.kind) {
case RAD_NORM_NFC: text = unorm_utf8(text, false, true); break;
case RAD_NORM_NFKC: text = unorm_utf8(text, true, true); break;
case RAD_NORM_NFD: text = unorm_utf8(text, false, false); break;
case RAD_NORM_NFKD: text = unorm_utf8(text, true, false); break;
case RAD_NORM_LOWERCASE: {
std::vector<uint32_t> cpts = unicode_cpts_from_utf8(text);
std::string out;
out.reserve(text.size());
for (uint32_t c : cpts) out += unicode_cpt_to_utf8(unicode_tolower(c));
text.swap(out);
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(). */
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;
if (s.flags & 2) while (b > a && unicode_cpt_flags_from_cpt(cpts[b-1]).is_whitespace) --b;
std::string out;
for (size_t i = a; i < b; ++i) out += unicode_cpt_to_utf8(cpts[i]);
text.swap(out);
break;
}
case RAD_NORM_REPLACE: apply_replace(text, s); break;
case RAD_NORM_PREPEND: text = s.arg0 + text; break;
default:
RAD_WARN("tokenizer: normaliser step %u is not implemented; text passed through",
s.kind);
break;
}
}
/* --- pre-tokenisers ---------------------------------------------------------------------- */
enum { SPLIT_REMOVED = 0, SPLIT_ISOLATED = 1, SPLIT_MERGED_PREV = 2,
SPLIT_MERGED_NEXT = 3, SPLIT_CONTIGUOUS = 4 };
void apply_split(std::vector<std::string>& words, const VocabStep& s) {
const std::string pat = canonicalise_pattern(s.arg0);
const std::vector<std::string> exprs = { pat };
std::vector<std::string> out;
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. */
std::vector<std::string> parts;
try {
parts = unicode_regex_split(w, exprs, /*byte_encode=*/false);
} catch (const std::exception& e) {
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. */
for (std::string& p : parts) if (!p.empty()) out.push_back(std::move(p));
}
words.swap(out);
}
void apply_bytelevel(std::vector<std::string>& words, const VocabStep& s) {
const bool add_prefix_space = (s.flags & 1) != 0;
const bool use_regex = (s.flags & 2) != 0;
if (add_prefix_space && !words.empty() && !words[0].empty() && words[0][0] != ' ') {
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. */
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)";
split.iarg = SPLIT_ISOLATED;
apply_split(words, split);
}
for (std::string& w : words) w = byte_encode(w);
}
void apply_metaspace(std::vector<std::string>& words, const VocabStep& s) {
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 (w.empty() || w.compare(0, 1, " ") != 0) w.insert(0, " ");
}
replace_all(w, " ", rep);
}
if (!split) return;
std::vector<std::string> out;
for (const std::string& w : words) {
size_t i = 0;
while (i < w.size()) {
size_t j = w.find(rep, i + (w.compare(i, rep.size(), rep) == 0 ? rep.size() : 0));
if (j == std::string::npos) { out.push_back(w.substr(i)); break; }
out.push_back(w.substr(i, j - i));
i = j;
}
if (w.empty()) out.push_back(w);
}
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) {
std::vector<std::string> out;
for (const std::string& w : words) {
const std::vector<uint32_t> cpts = unicode_cpts_from_utf8(w);
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;
}
std::string piece;
for (size_t k = i; k < j; ++k) piece += unicode_cpt_to_utf8(cpts[k]);
out.push_back(std::move(piece));
i = j;
}
}
words.swap(out);
}
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);
}
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);
}
} /* namespace */
std::vector<std::string> split(const std::string& pattern, const std::string& word) {
VocabStep s;
s.kind = RAD_PRE_SPLIT;
s.arg0 = pattern;
s.iarg = SPLIT_ISOLATED;
std::vector<std::string> words = { word };
apply_split(words, s);
return words;
}
bool structural(const std::string& pattern) { return pattern_is_structural(pattern); }
namespace {
int run_pre(const Vocab& v, const std::string& text, std::vector<std::string>& words) {
std::string t = text;
for (const VocabStep& s : v.steps()) if (step_is_norm(s.kind)) apply_norm(t, s);
words.assign(1, t);
for (const VocabStep& s : v.steps()) {
if (!step_is_pre(s.kind)) continue;
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_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. */
break;
default:
RAD_ERR("tokenizer: pre-tokeniser step %u is not implemented", s.kind);
return RAD_E_UNSUPPORTED;
}
}
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. */
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 {
int left, right, rank;
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. */
return rank > o.rank || (rank == o.rank && left > o.left);
}
};
std::vector<Symbol> symbols, final_syms;
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). */
bool have_byte_fallback = false;
bool have_bytelevel = false;
for (const VocabStep& s : v.steps()) {
if (s.kind == RAD_PRE_BYTE_FALLBACK) have_byte_fallback = true;
if (s.kind == RAD_PRE_BYTELEVEL) have_bytelevel = true;
}
for (const std::string& word : words) {
if (word.empty()) continue;
work = std::priority_queue<Bigram>();
symbols.clear();
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 STILL GO THROUGH THE MERGE LOOP, which is HuggingFace's
* behaviour at `ignore_merges: false` and is what every checkpoint in scope declares.
* A vocabulary setting it TRUE wants the same short-circuit for any word that is already
* a token, and this engine does not read the flag: core/text/tokenizer_json.cpp does not
* parse it and the vocabulary has nowhere to carry it. Such a model would tokenise
* differently here than it does in transformers -- silently, and mostly on rare words.
* Supporting it is a vocabulary field, not a change to this loop. */
if (v.find(word) >= 0 && v.type(v.find(word)) == RAD_TT_USER_DEFINED) {
symbols.push_back({ -1, -1, word.c_str(), word.size() });
offset = word.size();
}
while (offset < word.size()) {
Symbol sym;
const size_t len = std::min(unicode_len_utf8(word[offset]), word.size() - offset);
sym.text = word.c_str() + offset;
sym.n = len;
offset += len;
sym.prev = index - 1;
sym.next = offset == word.size() ? -1 : index + 1;
++index;
symbols.push_back(sym);
}
auto offer = [&](int l, int r) {
if (l == -1 || r == -1) return;
const std::string lt(symbols[l].text, symbols[l].n);
const std::string rt(symbols[r].text, symbols[r].n);
const int32_t rank = v.merge_rank(lt, rt);
if (rank < 0) return;
work.push({ l, r, rank, lt.size() + rt.size(), lt + rt });
};
for (int i = 1; i < (int)symbols.size(); ++i) offer(i - 1, i);
while (!work.empty()) {
const Bigram b = work.top();
work.pop();
Symbol& l = symbols[b.left];
Symbol& r = symbols[b.right];
if (l.n == 0 || r.n == 0) continue;
if (std::string(l.text, l.n) + std::string(r.text, r.n) != b.text) continue;
l.n += r.n;
r.n = 0;
l.next = r.next;
if (r.next >= 0) symbols[r.next].prev = b.left;
offer(l.prev, b.left);
offer(b.left, l.next);
}
for (Symbol& s : symbols) {
if (s.n == 0) continue;
s.prev = final_prev;
s.next = -1;
if (final_prev != -1) final_syms[final_prev].next = (int)final_syms.size();
final_syms.push_back(s);
final_prev = (int)final_syms.size() - 1;
}
}
for (int i = final_syms.empty() ? -1 : 0; i != -1; i = final_syms[i].next) {
const Symbol& s = final_syms[i];
if (s.n == 0) continue;
const std::string str(s.text, s.n);
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>". */
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);
const int32_t b = v.find(str.substr(k, n));
if (b >= 0) out.push_back(b);
else RAD_WARN("tokenizer: no token for byte-level piece '%s'",
str.substr(k, n).c_str());
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);
if (b >= 0) out.push_back(b);
else if (v.unk() >= 0) out.push_back(v.unk());
}
} else if (v.unk() >= 0) {
out.push_back(v.unk());
} else {
RAD_WARN("tokenizer: piece '%s' is not in the vocab and the chain declares neither "
"ByteLevel nor ByteFallback; it is dropped", str.c_str());
}
}
}
/* 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. */
void unigram(const Vocab& v, const std::string& text, std::vector<int32_t>& out) {
if (text.empty()) return;
const size_t n = text.size();
struct Best { int32_t id; size_t from; double score; };
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. */
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;
}
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);
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;
if (l == cp_len) matched_whole_cp = true;
const double sc = v.type(id) == RAD_TT_USER_DEFINED ? 0.0 : (double)v.score(id);
const double cand = best[i].score + sc;
if (cand > best[i + l].score) best[i + l] = { id, i, cand };
}
if (!matched_whole_cp) {
const double cand = best[i].score + unk_penalty;
if (cand > best[i + cp_len].score) best[i + cp_len] = { v.unk(), i, cand };
}
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. */
const int32_t unk = v.unk();
bool byte_fallback = false;
if (unk < 0)
for (const VocabStep& s : v.steps())
if (s.kind == RAD_PRE_BYTE_FALLBACK) byte_fallback = true;
const size_t start = out.size();
size_t dropped = 0;
bool prev_unk = false;
for (size_t pos = n; ; ) {
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;
if (id >= 0) out.push_back(id);
else ++dropped;
}
} else if (!(prev_unk && is_unk)) {
out.push_back(b.id);
}
if (b.from == 0) break;
prev_unk = is_unk;
pos = b.from;
}
std::reverse(out.begin() + start, out.end());
if (dropped)
RAD_WARN("tokenizer: %zu byte(s) of this text have no piece in the vocab, which has no unk "
"token and %s; they are dropped", dropped,
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. */
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;
while (i < w.size()) {
size_t j = w.size();
int32_t id = -1;
for (; j > i; --j) {
std::string sub = w.substr(i, j - i);
if (i > 0) sub = "##" + sub;
id = v.find(sub);
if (id >= 0) break;
}
if (id < 0) { ok = false; break; }
piece.push_back(id);
i = j;
}
if (ok) out.insert(out.end(), piece.begin(), piece.end());
else if (v.unk() >= 0) out.push_back(v.unk());
}
}
} /* namespace */
int encode(const Vocab& v, std::string_view text, std::vector<int32_t>& out,
bool add_special, bool parse_special) {
if (!v.ready()) return RAD_E_STATE;
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. */
struct Frag { bool is_token; int32_t id; size_t off, len; };
std::vector<Frag> frags;
const std::string raw(text);
frags.push_back({ false, -1, 0, raw.size() });
for (int32_t sid : v.special_ids()) {
const uint8_t t = v.type(sid);
if (!parse_special && (t == RAD_TT_CONTROL || t == RAD_TT_UNKNOWN)) continue;
const std::string& st = v.text(sid);
if (st.empty()) continue;
std::vector<Frag> next;
next.reserve(frags.size());
for (const Frag& f : frags) {
if (f.is_token) { next.push_back(f); continue; }
size_t pos = f.off;
const size_t end = f.off + f.len;
for (;;) {
const size_t m = raw.find(st, pos);
if (m == std::string::npos || m + st.size() > end) break;
if (m > pos) next.push_back({ false, -1, pos, m - pos });
next.push_back({ true, sid, m, st.size() });
pos = m + st.size();
}
if (pos < end) next.push_back({ false, -1, pos, end - pos });
}
frags.swap(next);
}
for (const Frag& f : frags) {
if (f.is_token) { out.push_back(f.id); continue; }
if (f.len == 0) continue;
const std::string chunk = raw.substr(f.off, f.len);
std::vector<std::string> words;
RAD_TRY(run_pre(v, chunk, words));
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. */
std::string joined;
for (const std::string& w : words) joined += w;
unigram(v, joined, out);
break;
}
default:
RAD_ERR("tokenizer: kind %u has no encoder", v.kind());
return RAD_E_UNSUPPORTED;
}
}
if (add_special && v.add_eos() && v.eos() >= 0) out.push_back(v.eos());
return RAD_OK;
}
} /* namespace tokref */
} /* namespace rad */
+48
View File
@@ -0,0 +1,48 @@
/* tokref.h -- a 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.
*
* 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:
* - `(?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.
* - llama.cpp's category tables are Unicode 15.1; the Oniguruma in tokenizers is 16.0. The 5185
* codepoints assigned in 16.0 (Garay, Todhri, Tulu-Tigalari, ..., new CJK strokes and Latin
* letters) are unassigned here and categorised there.
* - `\p{Han}+` is llama.cpp's name for its Kimi-K2 splitter, which does not implement K2's
* 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.
* - A regex Replace normaliser runs std::regex (ECMAScript, bytes) and expands `$` in its
* replacement; HuggingFace inserts the replacement verbatim.
*/
#pragma once
#include "text/tokenizer.h"
#include <string>
#include <string_view>
#include <vector>
namespace rad {
namespace tokref {
/* Same contract as Tokenizer::encode. */
int encode(const Vocab& v, std::string_view text, std::vector<int32_t>& out,
bool add_special, bool parse_special);
/* One word through one Split pattern, Isolated, as the reference splits it. */
std::vector<std::string> split(const std::string& pattern, const std::string& word);
/* True when llama.cpp has a hand-written splitter for `pattern` (after the (?i) rewrite). */
bool structural(const std::string& pattern);
} /* namespace tokref */
} /* namespace rad */
+101
View File
@@ -0,0 +1,101 @@
/* vmemprobe -- 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.
*
* 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.
*
* 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. */
#include <hip/hip_runtime.h>
#include <cstdio>
#include <cstdlib>
#include <vector>
static size_t G = 0;
static hipMemAllocationProp prop{};
static hipMemAccessDesc desc{};
static double freem() { size_t fr = 0, tot = 0; (void)hipMemGetInfo(&fr, &tot); return fr / 1048576.0; }
static double reach(int cap_gib) {
std::vector<void*> got; size_t n = 0; const size_t step = 128ull << 20;
for (;;) { void* p = nullptr;
if (hipMalloc(&p, step) != hipSuccess) break;
got.push_back(p); n += step; if (n > (size_t)cap_gib << 30) break; }
for (void* p : got) (void)hipFree(p);
return n / 1048576.0;
}
/* keep_handle: hold the allocation handle past the map, and release it only at the end. */
static void trial(const char* what, bool keep_handle, bool piecewise, bool free_va) {
const size_t bytes = (4ull << 30) / G * G;
void* base = nullptr;
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; }
if (!keep_handle) (void)hipMemRelease(h);
(void)hipMemSetAccess(base, bytes, &desc, 1);
const double f1 = freem();
if (piecewise) {
const size_t chunk = bytes / 8 / G * G;
for (int i = 0; i < 8; ++i) (void)hipMemUnmap((char*)base + (size_t)i * chunk, chunk);
} else {
(void)hipMemUnmap(base, bytes);
}
if (keep_handle) (void)hipMemRelease(h);
const double f2 = freem();
if (free_va) (void)hipMemAddressFree(base, bytes);
const double f3 = freem();
printf("%-34s free: %8.1f -> %8.1f (mapped) -> %8.1f (let go) -> %8.1f (va freed) reach %8.1f\n",
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. */
static void cycle(int n) {
const size_t total = (8ull << 30) / G * G;
const size_t part = (2ull << 30) / G * G;
void* base = nullptr;
if (hipMemAddressReserve(&base, total, G, nullptr, 0) != hipSuccess) { printf("cycle: reserve failed\n"); return; }
printf("\ncycle: %.1f GiB reservation held, %.1f GiB mapped and unmapped inside it\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; }
(void)hipMemRelease(h);
(void)hipMemSetAccess(base, part, &desc, 1);
const double fm = freem();
(void)hipMemUnmap(base, part);
printf(" pass %d: mapped %8.1f unmapped %8.1f MiB free\n", i, fm, freem());
}
(void)hipMemAddressFree(base, total);
printf("cycle: %.1f MiB free once the reservation itself is freed\n\n", freem());
}
int main(int argc, char** argv) {
const int dev = argc > 1 ? atoi(argv[1]) : 0;
if (hipSetDevice(dev) != hipSuccess) { printf("no device %d\n", dev); return 1; }
prop.type = hipMemAllocationTypePinned;
prop.location.type = hipMemLocationTypeDevice;
prop.location.id = dev;
desc.location = prop.location; desc.flags = hipMemAccessFlagsProtReadWrite;
size_t gr = 0, gm = 0;
(void)hipMemGetAllocationGranularity(&gr, &prop, hipMemAllocationGranularityRecommended);
(void)hipMemGetAllocationGranularity(&gm, &prop, hipMemAllocationGranularityMinimum);
G = gr ? gr : 4096;
printf("granularity: recommended %zu, minimum %zu\n", gr, gm);
printf("baseline reach %.1f MiB, free %.1f MiB\n\n", reach(24), freem());
trial("release-then-unmap", false, false, false);
cycle(8);
trial("release-then-unmap, va freed", false, false, true);
trial("unmap-then-release", true, false, false);
trial("piecewise unmap", false, true, false);
trial("piecewise unmap, va freed", false, true, true);
return 0;
}