Merge upstream main (v1.17.0 -> v2.1.0) into the SYCL port

102 upstream commits. Nine conflicts resolved. Fork side of the merge:
- libxe2: declare the givens_dense_quant schema (upstream 2.0 dropped it
  from libavx and libref; the device libraries now each carry it).
- plain_norm becomes an ABI 42 append to RadBuildCtx; abi layout table
  regenerated, kTableAbi = 42.

Known before the PR: arch_test (MTP lint and pinned graph hashes for
qwen35_fp8, qwen35moe_fp8, qwen4exp with MTP).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
aneinanderandClaude Opus 5.5 committed 2026-11-18 15:06:17 +01:00
commit 4b70a96378
850 files changed
+157819 -58519

No files matched your search

+7 -2
View File
@@ -1,4 +1,4 @@
# tools/ -- rad-info, rad-convert, rad-kbench, rad-tune, and the smaller checkers below.
# tools/ -- rad-info, rad-convert, rad-kbench, rad-tune, rad-yaml, and the smaller checkers below.
#
# rad_add_tool tools link rad_core: rad-convert, rad-kbench and rad-tune are the engine's startup
# with a different last step, loading the same plugins in the same hierarchy and running the same
@@ -50,6 +50,11 @@ add_executable(rad-tokcheck rad_tokcheck.cpp ${CMAKE_CURRENT_SOURCE_DIR}/iface.c
target_link_libraries(rad-tokcheck PRIVATE rad_tokref rad_core)
set_target_properties(rad-tokcheck PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
# rad-yaml writes a command line as the YAML configuration; it parses flags and nothing else.
add_executable(rad-yaml rad_yaml.cpp)
target_link_libraries(rad-yaml PRIVATE rad_core)
set_target_properties(rad-yaml PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
# rad-schemas links no core: it dlopens plugins and reads their static schema tables, so it works on
# a plugin the engine cannot load.
add_executable(rad-schemas rad_schemas.cpp)
@@ -81,7 +86,7 @@ set_target_properties(rad-gbnf-check PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE
# rad-schemas matters most in an installed prefix: it needs only the four exports every kernel
# plugin has, so it can debug an out-of-tree plugin the engine cannot load.
install(TARGETS rad-info rad-convert rad-kbench rad-tune rad-schemas rad-tokcheck
install(TARGETS rad-info rad-convert rad-kbench rad-tune rad-schemas rad-tokcheck rad-yaml
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
# rad-chatparse: the reply parser's acceptance run against a checkpoint's real tokenizer and chat
+2 -2
View File
@@ -43,7 +43,7 @@
#include "llama/common/chat.h"
#include "llama/common/jinja/runtime.h"
#include <nlohmann/json.hpp>
#include "util/json.h"
#include <cstdio>
#include <cstring>
@@ -54,7 +54,7 @@
#include <vector>
using namespace rad;
using ojson = nlohmann::ordered_json;
using ojson = Json;
namespace {
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""dashboard_embed.py write|check -- the dashboard's page as the header the engine compiles in.
The page is built from dashboard/ by Node (npm run build -> dashboard/dist/index.html: one document
with its script, style and type inlined). The engine's build has no Node, so the built page is
committed as core/server/dashboard_page.h and this keeps the two together:
write turns dashboard/dist/index.html into the header, records a digest of the sources it was
built from, and copies the build's list of bundled packages and their licences to
dashboard/THIRD-PARTY-LICENSES.txt (`npm run embed` in dashboard/ builds and writes)
check exits 1 if dashboard/'s sources no longer have the recorded digest: someone changed the
page's source and did not rebuild the header (the ctest `dashboard_page`)
The digest lives inside the header and only proves sources and claim agree; the served bytes are
hashed from outside by tests/ARTIFACTS (the ctest `artifact_sums`), so tampering with the header
alone fails. After a real rebuild, re-record both in the same commit:
sha256sum $(awk '{print $2}' tests/ARTIFACTS) > tests/ARTIFACTS
"""
import hashlib, os, sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DASH = os.path.join(ROOT, "dashboard")
HEADER = os.path.join(ROOT, "core", "server", "dashboard_page.h")
DELIM = "RADPAGE"
TOP = ["index.html", "package.json", "package-lock.json", "vite.config.ts", "components.json",
"tsconfig.json", "tsconfig.app.json", "tsconfig.node.json"]
def sources():
out = [os.path.join(DASH, f) for f in TOP if os.path.exists(os.path.join(DASH, f))]
for d, _, files in os.walk(os.path.join(DASH, "src")):
out += [os.path.join(d, f) for f in files]
return sorted(out)
def digest():
h = hashlib.sha256()
for p in sources():
h.update(os.path.relpath(p, DASH).replace(os.sep, "/").encode() + b"\0")
h.update(hashlib.sha256(open(p, "rb").read()).digest())
return h.hexdigest()
# The interfaces of dashboard/src/lib/api.ts that describe a route's object, and the name the
# engine's test knows each object by.
READS = [("Stats", "stats"), ("RunningRequest", "requests"), ("DraftPosition", "draft_positions"),
("Experts", "experts"), ("ExpertTier", "tiers"), ("Sessions", "sessions"), ("Session", "session")]
def reads():
"""Every "object.field" the page reads: the members of those interfaces, nested ones aside."""
src = open(os.path.join(DASH, "src", "lib", "api.ts"), encoding="utf-8").read()
out = []
for iface, obj in READS:
at = src.index("export interface %s {" % iface)
i = src.index("{", at) + 1
depth, word, start = 0, "", True
while depth >= 0:
c = src[i]
if c in "{([<":
depth += 1
elif c in "})]>":
depth -= 1
elif depth == 0:
if c in ";\n":
word, start = "", True
elif start and (c.isalnum() or c == "_"):
word += c
elif c in "?:" and start and word:
out.append(obj + "." + word)
word, start = "", False
elif not c.isspace():
start = False if not word else start
i += 1
return out
def recorded():
with open(HEADER, encoding="utf-8") as f:
for line in f:
if "kPageSources" in line and '"' in line:
return line.split('"')[1]
return None
def write():
page = open(os.path.join(DASH, "dist", "index.html"), encoding="utf-8").read()
# The licences of what the page bundles, as the build listed them, go where the header goes.
notices = open(os.path.join(DASH, "dist", "THIRD-PARTY-LICENSES.txt"), encoding="utf-8").read()
with open(os.path.join(DASH, "THIRD-PARTY-LICENSES.txt"), "w", encoding="utf-8") as f:
f.write(notices)
if ")" + DELIM + '"' in page:
sys.exit("the page contains the raw string's closing delimiter")
# A string literal's length is bounded on some compilers; adjacent literals join without one.
step = 12000
parts = [page[i:i + step] for i in range(0, len(page), step)]
body = "\n".join('R"%s(%s)%s"' % (DELIM, p, DELIM) for p in parts)
with open(HEADER, "w", encoding="utf-8") as f:
f.write("""/* core/server/dashboard_page.h -- the dashboard's page: one document with its script, style and
* type inlined, so the engine serves it from memory with no asset directory and no fetch from
* another origin (it runs on machines with no route to one).
*
* GENERATED by tools/dashboard_embed.py from the build of dashboard/; edit the sources there and
* run `npm run embed` in that directory. The ctest `dashboard_page` fails while the sources and
* this file disagree.
*/
#pragma once
/* A digest of dashboard/'s sources as of this build of the page. */
static const char* const kPageSources = "%s";
/* Every field the page reads of a route's object, as "object.field": the members of the
* interfaces in dashboard/src/lib/api.ts, which the page's compiler holds it to. Ends with null. */
static const char* const kPageReads[] = {
%s
nullptr
};
static const char* const kPage =
%s;
""" % (digest(), "\n".join(' "%s",' % r for r in reads()), body))
print("wrote %s: %d bytes of page in %d pieces, sources %s" % (os.path.relpath(HEADER, ROOT), len(page.encode()), len(parts), digest()[:12]))
def check():
have, want = recorded(), digest()
if have != want:
print("core/server/dashboard_page.h was built from other sources than dashboard/ holds now\n"
" recorded %s\n sources %s\nrun `npm run embed` in dashboard/ and commit the header" % (have, want))
sys.exit(1)
print("dashboard_page.h matches dashboard/ (%s)" % want[:12])
if __name__ == "__main__":
{"write": write, "check": check}.get(sys.argv[1] if len(sys.argv) > 1 else "", lambda: sys.exit(__doc__))()
-195
View File
@@ -1,195 +0,0 @@
/* dashcheck -- run the dashboard's own script against a sequence of real /stats payloads and
* report NaN, undefined, Infinity, a throw, or a badly formatted figure.
*
* The dashboard is one page driven by one endpoint, so its failures are arithmetic, not layout (a
* rate differenced over a zero interval, a model with no expert plane, a counter that went
* backwards). Those need real payloads in sequence, which no browser adds anything to.
*
* poll() catches whatever update() throws and only marks the dot stale, so a page that cannot
* render looks like a server that stopped answering. The exception is intercepted where it is
* caught, and "dot stale" afterwards means update() threw.
*
* The page formats every number through one block of functions (three significant figures rounded
* before the unit is chosen, binary sizes, decimal rates, SI prefixes, shares that never round onto
* 0% or 100%). Those run against a table of boundary cases first; then every text the polls write
* is searched for a raw float, four digits in front of a unit or prefix, or a thousands separator.
*
* node tools/dashcheck.js <saved dashboard html> <json array of /stats payloads>
*
* Capture the payloads under load: every rate on the page is a difference, which idle payloads do
* not exercise.
*/
const fs = require('fs');
const html = fs.readFileSync(process.argv[2], 'utf8');
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;
/* setMetric writes firstChild.nodeValue, not textContent, so every stub needs a text node; a
* stub without one throws inside the page's own try/catch and looks like a real bug. */
const tn = { nodeType: 3, _v: '' };
Object.defineProperty(tn, 'nodeValue', {
get(){ return tn._v; },
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;
/* Record what update() throws at the one place poll() catches it. */
js = js.replace('$("dot").className = "dot stale";',
'globalThis.__err = globalThis.__err || e; $("dot").className = "dot stale";');
js += "\n;globalThis.__poll = typeof poll === 'function' ? poll : null;";
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; }
/* Unit boundaries, where a formatter that picks its unit before rounding prints a figure the
* next unit up should replace. Each value sits on or just either side of one. */
const G = 2 ** 30, T = 2 ** 40, NB = '\u202f';
const CASES = [
['hb', [0], '0 B'], ['hb', [999], '999 B'], ['hb', [1023], '1.00 KiB'], ['hb', [1536], '1.50 KiB'],
['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, and poll() returns early while it is hidden. */
get('view-dash').hidden = false;
for (let i = 0; i < payloads.length + 1; i++) {
try { if (globalThis.__poll) await globalThis.__poll(); } catch (e) { threw = threw || e; }
}
/* "dot stale" means update() threw (see the header). */
const dot = els.has('dot') ? els.get('dot').className : '(never set)';
console.log(' dot after last poll: ' + dot);
if (/stale/.test(dot)) console.log(' UPDATE THREW (dashboard would read as stale, not broken)');
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);
})();
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Fit a candidate W6NL E4M3-exact codebook without loading/serving a model.
Samples BF16 down-projection weight rows from safetensors in disjoint layer sets.
This is a weight-distribution pilot, not held-out activation-weighted GPTQ validation.
"""
import argparse, json, struct, pathlib
import numpy as np
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('checkpoint', type=pathlib.Path, help='original BF16 checkpoint directory')
ROOT = parser.parse_args().checkpoint
INDEX = json.loads((ROOT / 'model.safetensors.index.json').read_text())['weight_map']
def sample(layers, seed):
rng = np.random.default_rng(seed)
chunks = []
for layer in layers:
name = f'model.language_model.layers.{layer}.mlp.experts.down_proj'
path = ROOT / INDEX[name]
with path.open('rb') as f:
n = struct.unpack('<Q', f.read(8))[0]
m = json.loads(f.read(n))[name]
assert m['dtype'] == 'BF16' and m['shape'] == [512, 2560, 640], m
base = 8 + n + m['data_offsets'][0]
for e in rng.choice(512, size=5, replace=False):
start = int(rng.integers(0, 2560 - 128))
f.seek(base + (int(e) * 2560 + start) * 640 * 2)
b = f.read(128 * 640 * 2)
assert len(b) == 128 * 640 * 2
u = np.frombuffer(b, dtype='<u2').astype(np.uint32) << 16
x = u.view(np.float32).reshape(-1, 128).copy()
for width in (1,2,4,8,16,32,64):
v = x.reshape(-1, 128//(2*width), 2, width)
a, c = v[:,:,0,:].copy(), v[:,:,1,:].copy()
v[:,:,0,:] = a+c
v[:,:,1,:] = a-c
v = np.abs(x.reshape(-1,64))
mx = np.max(v, axis=1, keepdims=True)
v /= np.maximum(mx, 1e-30)
chunks.append(v.reshape(-1))
x = np.concatenate(chunks)
assert np.all(np.isfinite(x))
return x
def hist(x, bins=4096):
# Preserve the amax=1 endpoint in the last bin.
idx = np.minimum((x*bins).astype(np.int32),bins-1)
return np.bincount(idx, minlength=bins).astype(np.float64)
def e4(b):
exponent, mant = b >> 3, b & 7
if exponent == 0: return mant * 2**-9
return (1 + mant/8) * 2**(exponent-7)
def score(h, vals, scale, x):
u = np.asarray(vals, dtype=np.float64)/scale
i = np.searchsorted((u[1:]+u[:-1])/2, x)
return float(np.sum(h*(x-u[i])**2)/h.sum())
def fit(h):
x=(np.arange(len(h))+.5)/len(h)
centers = np.linspace(0.01, 0.99, 32)
for _ in range(2500):
i=np.searchsorted((centers[1:]+centers[:-1])/2,x)
counts=np.bincount(i, weights=h, minlength=32)
sums=np.bincount(i, weights=h*x, minlength=32)
new=np.divide(sums, counts, out=centers.copy(), where=counts>0)
if np.max(np.abs(new-centers)) < 1e-9: break
centers=new
i=np.searchsorted((centers[1:]+centers[:-1])/2,x)
counts=np.bincount(i, weights=h, minlength=32)
vals=np.array([e4(b) for b in range(1,127)],dtype=np.float64)
best=None
for scale in np.arange(20.,80.01,.5):
# Find 32 strictly increasing, exactly representable positive fp8 levels.
cost=counts[:,None]*(centers[:,None]-vals[None,:]/scale)**2
dp=cost[0].copy(); parents=[]
for j in range(1,32):
prev=np.r_[np.inf, dp[:-1]]
arg=np.minimum.accumulate(prev)
inds=np.empty(len(vals),np.int32); k=-1; m=np.inf
for z,p in enumerate(prev):
if p<m: m=p; k=z-1
inds[z]=k
dp=cost[j]+arg; parents.append(inds)
# Force the outermost magnitude near amax: production scale search starts at amax/peak.
# Do not spend levels beyond 1 merely because empty high-end Lloyd cells cost nothing.
eligible=np.where((vals >= scale * .98) & (vals <= scale * 1.02),dp,np.inf)
z=int(np.argmin(eligible)); chosen=[z]
for parent in reversed(parents):
z=int(parent[z]); chosen.append(z)
chosen=chosen[::-1]
if min(chosen)<0: continue
table=vals[chosen]
err=score(h,table,scale,x)
if best is None or err<best[0]: best=(err,scale,table.copy())
return best
a=sample([0,8,16,24,32,40,47],20261116)
b=sample([4,12,20,28,36,44],20261117)
h,hh=hist(a),hist(b); x=(np.arange(len(h))+.5)/len(h)
err,scale,tab=fit(h)
w5=[.8125,2.5,4,5.5,7.5,9,11,12,14,16,18,20,22,24,26,30]
# Optimize one scalar on each sampled distribution, analogous to scale search; not GPTQ.
for label,table in [('W5',w5),('W6',tab)]:
for split,weights in [('fit',h),('heldout',hh)]:
e,s=min((score(weights,table,s,x),s) for s in np.arange(20.,80.01,.1))
print(label,split,'normalized MSE',round(e,9),'scale',round(s,2))
print('fit_count',len(a),'heldout_count',len(b),'candidate_scale',scale)
print('w6 magnitudes',', '.join(f'{v:g}' for v in tab))
print('e4m3 bytes',', '.join(f'0x{next(i for i in range(1,127) if e4(i)==v):02x}' for v in tab))
+24 -1
View File
@@ -193,6 +193,27 @@ int rad_operand_shapes(const std::string& op, const Geometry& g, int n_opd, int6
add((uint32_t)RAD_BF16, {M, N}); /* y */
add((uint32_t)RAD_F32, {K / group, (M + 15) / 16 * 16}); /* a_sum, group-major */
skip_opd(); /* b_ref */
} else if (q && (std::strcmp(q, "w5a8i8") == 0 || std::strcmp(q, "w4a8i8_asym") == 0)) {
/* The same grids against an int8 activation (libr4d/r4d_gemm_wpa8i8_tiled.hip):
* givens_dense_quant's int8 codes, parts side by side, with an f32 scale per (row,
* part, 128 of K). The weight is libr4d/r4d_layout.cpp's int4 / int5 form: a nibble
* plane of N*K/2 bytes, then (int5 only) a fifth-bit plane of N*K/8, and one dword per
* row and 128 of K holding the f16 scale and zero. Random bytes suffice for timing. */
if (N <= 0 || K <= 0 || group != 128 || (K % 128) || (N % 16))
return RAD_E_UNSUPPORTED;
const int64_t pb1 = gi("pb1", 0), pb2 = gi("pb2", 0);
const int64_t e1 = pb1 > 0 && pb1 < N ? pb1 : N;
int64_t e2 = pb2 > 0 && pb2 < N ? pb2 : N;
if (e2 < e1) e2 = e1;
const int64_t parts = e2 < N ? 3 : (e1 < N ? 2 : 1);
const bool five = std::strcmp(q, "w5a8i8") == 0;
add((uint32_t)RAD_I8, {M, parts * K}); /* a */
add((uint32_t)RAD_F32, {M, parts * (K / 128)}); /* a_scale */
add((uint32_t)RAD_U8, {N, five ? K * 5 / 8 : K / 2}); /* b */
add((uint32_t)RAD_U32, {N, K / group}); /* b_scale */
add((uint32_t)RAD_BF16, {M, N}); /* y */
skip_opd(); /* a_sum */
skip_opd(); /* b_ref */
} else {
const bool a8 = q && std::strcmp(q, "fp8a8") == 0;
const bool a16 = q && std::strcmp(q, "fp8a16") == 0;
@@ -224,6 +245,7 @@ int rad_operand_shapes(const std::string& op, const Geometry& g, int n_opd, int6
/* ---- the paged pair, sharing the layout stated in libref/ref_ops.h:
*
* kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim] K first, V second in a slot
* (2 * head_dim + 4 at the int8 cache: rad_kv_row_elems)
*
* The block count and context length are this tool's choice; any cache large enough for the
* case works as long as the indices land inside it. */
@@ -241,7 +263,8 @@ int rad_operand_shapes(const std::string& op, const Geometry& g, int n_opd, int6
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});
const uint32_t cd = kvd == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_BF16 : kvd;
add(cd, {nb, kvh, bs, rad_kv_row_elems(cd, head_dim)});
}
else if (op == "attn_paged") {
/* `M` is q_len (decode and prefill are different kernels, docs/OPS.md). One sequence whose
+2 -2
View File
@@ -25,8 +25,8 @@ SRC is a merged checkpoint (config.json + *.safetensors) or a PEFT adapter (adap
adapter_model.safetensors). OUT defaults to SRC's folder name + .rad beside SRC (or in out_dir).
Optional config ~/.config/rad-export/config.json (or --config):
{"image": "stilldeadcode/radiance", "out_dir": "/models/rad",
"recipes": {"Qwen3.8-27B": "q38-27b-fp8block-df2"}, # base-model substring -> recipe
"drafts": {"q38-27b-fp8block-df2": "/models/Qwen3.8-27B-DFlash2"}, # recipe -> drafter
"recipes": {"Qwen3.8-27B": "q38-27b-iq8r"}, # base-model substring -> recipe
"drafts": {"q38-27b-iq8r": "/models/Qwen3.8-27B-DFlash2"}, # recipe -> drafter
"bases": {"Qwen/Qwen3.8-27B": "/models/Qwen3.8-27B"}, # adapter base id -> local copy
"hub_cache": ["~/.cache/huggingface/hub"]}
Run from an Unsloth Studio post-export hook (UNSLOTH_POST_EXPORT set), the last line names the .rad
+8 -8
View File
@@ -28,7 +28,7 @@
* ("new"), and the streaming parser alone at sizes the legacy path cannot reach; and the host cost
* of one streamed token by component (decoder, server text bookkeeping, parser, reader bridge,
* chunk JSON, and the tool-call grammar's accept_token / fill_mask), with every SSE event checked
* against nlohmann's serialisation.
* against Json::dump's serialisation.
*
* Exit status is non-zero when any reply breaks the contract or a verdict is not allowed.
*
@@ -46,7 +46,7 @@
#include "text/token_view.h"
#include "text/tokenizer.h"
#include <nlohmann/json.hpp>
#include "util/json.h"
#include <algorithm>
#include <chrono>
@@ -198,9 +198,9 @@ void check_reply(const Bench& b, const Tok& t, const std::string& written, const
++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());
Json(m).dump().c_str(),
Json(written).dump(-1, ' ', false,
Json::error_handler_t::replace).c_str());
break;
}
}
@@ -211,8 +211,8 @@ void check_reply(const Bench& b, const Tok& t, const std::string& written, const
++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(),
Json(text).dump(-1, ' ', false,
Json::error_handler_t::replace).c_str(),
v.detail.c_str());
}
if (v.same) ++ty->same;
@@ -307,7 +307,7 @@ std::string per(const std::vector<double>& secs, size_t units) {
return b;
}
/* Every SSE event in `out` must round-trip byte for byte through nlohmann parse and dump, which
/* Every SSE event in `out` must round-trip byte for byte through Json parse and dump, which
* holds the non-DOM chunk writer to the DOM's output. Returns the events that do not. */
size_t sse_not_canonical(const std::string& out, size_t* events) {
size_t bad = 0;
+159 -52
View File
@@ -26,7 +26,7 @@
#include "rad_quant.h"
#include <dlfcn.h>
#include <nlohmann/json.hpp>
#include "util/json.h"
#include <sys/stat.h>
@@ -84,7 +84,7 @@ int clef_metadata(const std::string& in, const std::string& config_dir, const Ch
"checkpoint (or under --config)", path.c_str());
return -1;
}
nlohmann::json c;
Json c;
try { f >> c; } catch (const std::exception& e) {
RAD_ERR("%s: %s", path.c_str(), e.what());
return -1;
@@ -163,7 +163,7 @@ int laya_metadata(const std::string& in, const std::string& config_dir, MetaOwn&
dir = slash == std::string::npos ? "." : in.substr(0, slash);
}
}
auto read_json = [](const std::string& path, nlohmann::json* j) {
auto read_json = [](const std::string& path, Json* j) {
std::ifstream f(path);
if (!f) { RAD_ERR("%s: a Laya checkpoint carries it; cannot read it", path.c_str()); return -1; }
try { f >> *j; } catch (const std::exception& e) {
@@ -181,7 +181,7 @@ int laya_metadata(const std::string& in, const std::string& config_dir, MetaOwn&
if (enc.keys[i] != "model_type" && enc.keys[i] != "architectures") meta.set(enc.keys[i], enc.vals[i]);
meta.m = enc.m;
nlohmann::json rl;
Json rl;
if (read_json(dir + "/rl_agent_config.json", &rl) < 0) return -1;
const std::pair<const char*, long long> counts[] = { { "max_len", 1 }, { "head_max_len", 1 },
{ "head_layers", 0 } };
@@ -200,7 +200,7 @@ int laya_metadata(const std::string& in, const std::string& config_dir, MetaOwn&
auto num = [](double v) { char s[32]; std::snprintf(s, sizeof s, "%.9g", v); return std::string(s); };
std::string temps = "1 1 1";
if (rl.contains("temperature")) {
const nlohmann::json& t = rl["temperature"];
const Json& t = rl["temperature"];
if (!t.is_array() || t.size() != 3 || !t[0].is_number() || !t[1].is_number() || !t[2].is_number()) {
RAD_ERR("%s/rl_agent_config.json: `temperature` is not three numbers (choice, score, "
"noul)", dir.c_str());
@@ -217,10 +217,10 @@ int laya_metadata(const std::string& in, const std::string& config_dir, MetaOwn&
/* The special tokens by name (tokenizer_config.json), their ids from tokenizer.json. */
const std::string tdir = dir + "/tokenizer";
if (tokjson->empty()) *tokjson = tdir + "/tokenizer.json";
nlohmann::json tc, tj;
Json tc, tj;
if (read_json(tdir + "/tokenizer_config.json", &tc) < 0 || read_json(*tokjson, &tj) < 0) return -1;
for (const char* which : { "cls_token", "sep_token", "mask_token" }) {
const nlohmann::json* v = tc.contains(which) ? &tc[which] : nullptr;
const Json* v = tc.contains(which) ? &tc[which] : nullptr;
if (v && v->is_object() && v->contains("content")) v = &(*v)["content"];
if (!v || !v->is_string()) {
RAD_ERR("%s/tokenizer_config.json: no `%s`", tdir.c_str(), which);
@@ -346,8 +346,8 @@ void usage() {
" the engine. Default: the checkpoint's training context\n"
" --draft-model DIR a drafter that ships as its own repository (DFlash2), merged\n"
" under `draft.`\n"
" --kv-cache-dtype T bf16 | fp8, the cache width declare is run at. Default: the\n"
" first of bf16, fp8 at which every op resolves -- the container\n"
" --kv-cache-dtype T bf16 | i8, the cache width declare is run at. Default: the\n"
" first of bf16, i8 at which every op resolves -- the container\n"
" is the same at either, so this only picks the kernels it checks\n"
" --max-spec N the max_spec declare is run at (default 4, or the block a\n"
" drafter states; a number given here is used as given); 0\n"
@@ -373,11 +373,24 @@ void usage() {
" every target; several targets mean the module is their concate-\n"
" nation (a fused qkv), and the adapter's rows split along them\n"
" in the order listed\n"
" --in-place with --reuse: EXTEND that container instead of writing a new one.\n"
" --in-place with --reuse: EXTEND that container (the first --reuse; further\n"
" ones only supply planes) instead of writing a new one.\n"
" Its weights stay where they are; new ones are written past its\n"
" end and the header last. Refused when a weight it holds would\n"
" change or a new weight is an expert. <file>.pre-append keeps the\n"
" old header and length\n"
" change or a new weight is an expert of a layer it holds experts\n"
" of. <file>.pre-append keeps the old header and length\n"
" --replace GLOB with --in-place: a weight the glob matches that the container\n"
" holds under another encoding or rule is written again past its\n"
" end, and the old planes stay behind as unreachable bytes until\n"
" the container is converted to a new file (repeatable). A\n"
" layer's other experts move with one that is written again,\n"
" their planes copied\n"
" --defer GLOB leave every weight the glob matches out of this container, for\n"
" a later --in-place run to add (repeatable). With --in-place a\n"
" weight the container already holds stays. The container loads\n"
" once no weight is left out, so a checkpoint larger than the disk\n"
" converts a layer at a time: the first run defers the layers\n"
" whose tensors are not there yet, each later run adds some\n"
" --gpus LIST the cards (HIP device numbers, comma separated) the quantisers\n"
" may run on, and large weights then run two at a time. A\n"
" quantiser writes the same bytes on a card as on the host; with\n"
@@ -426,6 +439,8 @@ int main(int argc, char** argv) {
bool verbose = false, plan_only = false, list_quant = false;
std::string reuse_path, changed_path;
std::vector<std::string> reuse_more; /* --reuse given again: more containers to copy from */
std::vector<std::string> defer; /* --defer: globs of the weights this run leaves out */
std::vector<std::string> replace; /* --replace: globs of the weights --in-place may rewrite */
std::vector<std::string> lora_paths;
double lora_strength = 1.0;
std::string lora_map;
@@ -493,16 +508,18 @@ int main(int argc, char** argv) {
}
else if (a == "--lora-map") lora_map = next("--lora-map");
else if (a == "--in-place") in_place = true;
else if (a == "--defer") defer.push_back(next("--defer"));
else if (a == "--replace") replace.push_back(next("--replace"));
else if (a == "--gpus") {
for (const std::string& d : rad_split_list(next("--gpus")))
gpus.push_back((int)rad_flag_int("rad-convert", "--gpus", d.c_str(), 0, 1023));
}
else if (a == "--kv-cache-dtype") {
const std::string v = next("--kv-cache-dtype");
if (v == "fp8") kv_dtype = RAD_F8E4M3;
if (v == "i8") kv_dtype = RAD_I8;
else if (v == "bf16") kv_dtype = RAD_BF16;
else { std::fprintf(stderr, "rad-convert: --kv-cache-dtype takes bf16 "
"or fp8, not '%s'\n", v.c_str());
"or i8, not '%s'\n", v.c_str());
return 2; }
}
else if (a == "-v" || a == "--verbose") { verbose = true; log_set_level(Log::Debug); }
@@ -571,6 +588,11 @@ int main(int argc, char** argv) {
}
if (out.empty()) out = reuse_path;
}
if (!replace.empty() && !in_place) {
std::fprintf(stderr, "rad-convert: --replace names weights --in-place writes again; a "
"conversion to a new file writes every changed weight anyway\n");
return 2;
}
if (in.empty() || out.empty()) { usage(); return 2; }
/* The output is opened with O_TRUNC, so it must not be the --reuse container unless
* --in-place is given. */
@@ -663,12 +685,10 @@ int main(int argc, char** argv) {
RadFile reuse;
if (!reuse_path.empty() && reuse.open(reuse_path.c_str()) != RAD_OK) return 1;
/* Further --reuse containers supply only weights the first lacks or holds converted otherwise:
* a container assembled from several converts (a mixed-precision recipe). */
* a container assembled from several converts (a mixed-precision recipe). With --in-place the
* first is the container extended and the others supply the planes of weights written past
* its end. */
std::deque<RadFile> reuse_extra;
if (!reuse_more.empty() && in_place) {
std::fprintf(stderr, "rad-convert: --in-place extends one container; give --reuse once\n");
return 2;
}
for (const std::string& r : reuse_more) {
reuse_extra.emplace_back();
if (reuse_extra.back().open(r.c_str()) != RAD_OK) return 1;
@@ -926,12 +946,12 @@ int main(int argc, char** argv) {
return n;
};
/* The KV cache width is a serve-time choice the container does not record; only the kernels
* differ (an fp8-cache attention may have no bf16 form). Without --kv-cache-dtype, check
* differ (an int8-cache attention may have no bf16 form). Without --kv-cache-dtype, check
* against the first width at which every op resolves, else report the one with fewest holes. */
const std::vector<int> widths = kv_dtype != RAD_DT_INVALID
? std::vector<int>{ kv_dtype }
: std::vector<int>{ RAD_BF16, RAD_F8E4M3 };
auto width_name = [](int dt) { return dt == RAD_F8E4M3 ? "fp8" : "bf16"; };
: std::vector<int>{ RAD_BF16, RAD_I8 };
auto width_name = [](int dt) { return dt == RAD_I8 ? "i8" : "bf16"; };
Program prog;
size_t dead = 0;
for (size_t k = 0; k < widths.size(); ++k) {
@@ -1161,10 +1181,13 @@ int main(int argc, char** argv) {
};
std::vector<Job> jobs;
jobs.reserve(plan.size());
int64_t reused_inplace = 0, n_inplace = 0, n_changed = 0;
int64_t reused_inplace = 0, n_inplace = 0, n_changed = 0, n_deferred = 0;
std::vector<int64_t> defer_hits(defer.size(), 0);
std::vector<int64_t> replace_hits(replace.size(), 0);
int64_t n_replaced = 0, replaced_dead = 0;
for (Logical* Lp : plan) {
Logical& L = *Lp;
/* What the writer is told of a logical weight. */
auto weight_of = [](const Logical& L) {
RadWriter::Weight ww;
ww.name = L.src.name;
const RecipeRule* rr = L.rule ? L.rule->rule : L.import_rule;
@@ -1176,10 +1199,56 @@ int main(int argc, char** argv) {
ww.layer = L.layer;
ww.expert = L.expert;
ww.slot = L.slot;
return ww;
};
/* Whether container R holds `ww` as entry `e` with the planes this run would write: the same
* encoding, quantiser, options and shape, and for an expert the same place in its layer. */
auto held_same = [](const RadFile& R, const RadFileEntry& e, const RadWriter::Weight& ww) {
const bool expert = ww.expert >= 0 || e.expert >= 0;
bool same = rad_enc_equal(&R.encoding(e), &ww.enc) && ww.quantizer == R.str(e.quantizer) &&
ww.options == R.str(e.options) && e.rank == ww.rank &&
(!expert || (e.layer == ww.layer && e.expert == ww.expert &&
e.slot == ww.slot));
for (uint32_t i = 0; same && i < RAD_MAX_RANK; ++i)
if (e.shape[i] != ww.shape[i]) same = false;
return same;
};
auto replace_names = [&](const std::string& name) {
for (const std::string& g : replace)
if (recipe_glob(g.c_str(), name.c_str())) return true;
return false;
};
/* The layers whose experts --replace writes again: a layer's experts sit at one stride, so the
* ones whose rule did not change move with the ones whose did, their planes copied. */
std::unordered_set<int32_t> moved_layers;
if (in_place && !replace.empty())
for (const Logical* Lp : plan) {
if (Lp->expert < 0) continue;
const RadWriter::Weight ww = weight_of(*Lp);
const RadFileEntry* re = reuse.find(ww.name);
if (re && !held_same(reuse, *re, ww) && replace_names(ww.name))
moved_layers.insert(ww.layer);
}
int64_t n_moved = 0, moved_bytes = 0;
/* Written past the end of an --in-place container from another --reuse container's planes. */
int64_t n_from_other = 0, other_bytes = 0;
for (Logical* Lp : plan) {
Logical& L = *Lp;
RadWriter::Weight ww = weight_of(L);
int64_t plane_total = 0;
for (int k = 0; k < L.enc.n_planes; ++k)
plane_total += rad_enc_plane_bytes(&L.enc.plane[k], L.src.rows, L.src.cols);
/* --- Deferred: left for a later --in-place run, unless the container being extended holds
* it already. Its checkpoint tensors are not read. */
{
bool hit = false;
for (size_t d = 0; d < defer.size(); ++d)
if (recipe_glob(defer[d].c_str(), ww.name.c_str())) { ++defer_hits[d]; hit = true; }
if (hit && !(in_place && reuse.find(ww.name))) { ++n_deferred; continue; }
}
/* --- Reused: the same encoding, quantiser, options and shape in the --reuse container give
* the same planes, assuming the same checkpoint (the operator's responsibility; neither
* container records e.g. a Hessian's contents). */
@@ -1194,50 +1263,73 @@ int main(int argc, char** argv) {
/* The movement group is the declaration's either way (add_weight and add_existing
* record ww's), so a plugin that regroups a weight still reuses its planes; only an
* expert's layer, index and slot say where its planes sit in a stride table. */
const bool expert = ww.expert >= 0 || re->expert >= 0;
bool same = rad_enc_equal(&reuse.encoding(*re), &ww.enc) &&
ww.quantizer == reuse.str(re->quantizer) &&
ww.options == reuse.str(re->options) && re->rank == ww.rank &&
(!expert || (re->layer == ww.layer && re->expert == ww.expert &&
re->slot == ww.slot));
for (uint32_t i = 0; same && i < RAD_MAX_RANK; ++i)
if (re->shape[i] != ww.shape[i]) same = false;
const bool same = held_same(reuse, *re, ww);
if (in_place) {
if (!same) {
/* --replace: the weight is written again past the end and the old planes are
* left behind. Every glob that matches counts, as --defer's do. */
bool rep = false;
for (size_t d = 0; d < replace.size(); ++d)
if (recipe_glob(replace[d].c_str(), ww.name.c_str())) {
++replace_hits[d];
rep = true;
}
if (!same && !rep) {
RAD_ERR("--in-place: '%s' is in %s as %s by '%s %s', and this run would write "
"it as %s by '%s %s'. A weight cannot be replaced in place; convert "
"to a new file.", ww.name.c_str(), reuse_path.c_str(),
"it as %s by '%s %s'. Name it with --replace to write it again past "
"the end, or convert to a new file.", ww.name.c_str(),
reuse_path.c_str(),
enc_name(reuse.encoding(*re)).c_str(), reuse.str(re->quantizer),
reuse.str(re->options), enc_name(ww.enc).c_str(),
ww.quantizer.c_str(), ww.options.c_str());
w.abort();
return 1;
}
if (w.add_existing(ww, reuse, *re) < 0) { w.abort(); return 1; }
reused_inplace += (int64_t)re->bytes;
++n_inplace;
continue;
/* An unchanged expert of a layer that is written again goes with it: the same
* planes, copied past the end (the job below reads them from the container). */
const bool moved = same && ww.expert >= 0 && moved_layers.count(ww.layer) != 0;
if (same && !moved) {
if (w.add_existing(ww, reuse, *re) < 0) { w.abort(); return 1; }
reused_inplace += (int64_t)re->bytes;
++n_inplace;
continue;
}
if (moved) { ++n_moved; moved_bytes += (int64_t)re->bytes; }
else ++n_replaced;
replaced_dead += (int64_t)re->bytes;
}
if (!same) re = nullptr;
re = same ? re : nullptr;
}
RadFile* rf = re ? &reuse : nullptr;
for (size_t x = 0; !re && !reads_changed && x < reuse_extra.size(); ++x) {
RadFile& R = reuse_extra[x];
const RadFileEntry* e = R.find(ww.name);
if (!e) continue;
const bool expert = ww.expert >= 0 || e->expert >= 0;
bool same = rad_enc_equal(&R.encoding(*e), &ww.enc) && ww.quantizer == R.str(e->quantizer) &&
ww.options == R.str(e->options) && e->rank == ww.rank &&
(!expert || (e->layer == ww.layer && e->expert == ww.expert &&
e->slot == ww.slot));
for (uint32_t i = 0; same && i < RAD_MAX_RANK; ++i)
if (e->shape[i] != ww.shape[i]) same = false;
if (same) { re = e; rf = &R; }
if (held_same(R, *e, ww)) {
re = e;
rf = &R;
if (in_place) { ++n_from_other; other_bytes += (int64_t)e->bytes; }
}
}
const int64_t idx = w.add_weight(ww);
if (idx < 0) { w.abort(); return 1; }
jobs.push_back(Job{ Lp, idx, re, rf, plane_total });
}
/* A --replace glob no weight of the container matches is a typo too. */
for (size_t d = 0; d < replace.size(); ++d)
if (!replace_hits[d]) {
RAD_ERR("--replace %s matches no weight %s holds", replace[d].c_str(),
reuse_path.c_str());
w.abort();
return 1;
}
/* A --defer glob no weight matches is a typo; refuse it. */
for (size_t d = 0; d < defer.size(); ++d)
if (!defer_hits[d]) {
RAD_ERR("--defer %s matches no weight of this conversion", defer[d].c_str());
w.abort();
return 1;
}
/* A --changed name no weight reads is a typo or an unconverted tensor; refuse it. */
if (!changed.empty()) {
std::vector<std::string> unread;
@@ -1565,15 +1657,30 @@ int main(int argc, char** argv) {
RAD_INFO("wrote %s: %lld weight(s), %s of weights, %u vocab token(s)", out.c_str(),
(long long)w.weight_count(), humanb(written.load()).c_str(),
(unsigned)vb.tokens.size());
if (in_place)
if (in_place) {
RAD_INFO("--in-place: %lld weight(s), %s, kept where they were in %s; %lld added past "
"its end", (long long)n_reused.load(), humanb(reused.load()).c_str(),
reuse_path.c_str(), (long long)(w.weight_count() - n_reused.load()));
"its end", (long long)(n_reused.load() - n_moved - n_from_other),
humanb(reused.load() - moved_bytes - other_bytes).c_str(), reuse_path.c_str(),
(long long)(w.weight_count() - n_reused.load() + n_moved + n_from_other));
if (n_from_other)
RAD_INFO("--in-place: %lld of the added weight(s), %s, are another --reuse "
"container's planes", (long long)n_from_other, humanb(other_bytes).c_str());
if (n_replaced)
RAD_INFO("--replace: %lld of the added weight(s) replace one the container held and "
"%lld unchanged expert(s) of their layers moved with them, planes copied; "
"%s of old planes are unreachable until it is converted to a new file "
"(rad-info --unreferenced lists them)",
(long long)n_replaced, (long long)n_moved, humanb(replaced_dead).c_str());
}
else if (reuse.is_open())
RAD_INFO("--reuse: %lld weight(s), %s, copied from %s; the other %lld were written",
(long long)n_reused.load(), humanb(reused.load()).c_str(), reuse_path.c_str(),
(long long)(w.weight_count() - n_reused.load()));
if (n_deferred)
RAD_WARN("--defer: %lld weight(s) left out. The container does not load until --in-place "
"runs have added them", (long long)n_deferred);
std::vector<const Logical*> measured;
for (const Logical* L : plan) if (L->err >= 0) measured.push_back(L);
if (!measured.empty()) {
+2 -2
View File
@@ -42,7 +42,7 @@
#include "text/token_view.h"
#include "text/tokenizer.h"
#include <nlohmann/json.hpp>
#include "util/json.h"
#include <algorithm>
#include <chrono>
@@ -58,7 +58,7 @@
#include <unistd.h>
using namespace rad;
using ojson = nlohmann::ordered_json;
using ojson = Json;
using Clock = std::chrono::steady_clock;
namespace {
+87
View File
@@ -9,12 +9,15 @@
*/
#include "iface.h"
#include "format/encoding.h"
#include "format/recipe.h"
#include <algorithm>
#include <cinttypes>
#include <cstdio>
#include <cstring>
#include <map>
#include <utility>
#include <vector>
using namespace rad;
@@ -32,6 +35,12 @@ void usage() {
" --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"
" --unreferenced [N] print the byte ranges of at least N bytes (default 1048576)\n"
" that no table and no plane names, one `offset bytes` a line, and\n"
" stop: what `rad-convert --in-place --replace` left behind. Nothing\n"
" reads them, so `fallocate --punch-hole` gives their disk back.\n"
" --planes GLOB print the planes of every weight whose name the glob matches, one\n"
" `offset bytes name` a line, 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"
@@ -397,6 +406,74 @@ int print_plugins(const std::string& home) {
return 0;
}
/* ------------------------------------------------------------------ unreferenced bytes */
/* Every range of at least `min_bytes` that neither the header, a table it places, nor a plane of
* the directory covers, as `offset bytes` lines; a summary on stderr. A container written in one
* pass has only alignment padding between its planes; one extended in place also keeps the tables
* it had before and the planes of every weight it replaced. */
int print_unreferenced(const RadFile& f, int64_t min_bytes) {
const RadFileHeader& h = f.header();
std::vector<std::pair<uint64_t, uint64_t>> live; /* [first, last) */
auto add = [&](uint64_t off, uint64_t bytes) { if (bytes) live.emplace_back(off, off + bytes); };
add(0, sizeof(RadFileHeader));
add(h.str_off, h.str_bytes);
add(h.meta_off, h.meta_count * sizeof(RadFileKV));
add(h.dir_off, h.dir_count * sizeof(RadFileEntry));
add(h.plane_off, h.plane_count * sizeof(RadFilePlane));
add(h.enc_off, h.enc_count * sizeof(RadEncoding));
add(h.vocab_off, h.vocab_bytes);
add(h.prof_off, h.prof_count * sizeof(RadFileProfile));
add(h.reserved[RAD_HDR_AUX_VOCAB_OFF], h.reserved[RAD_HDR_AUX_VOCAB_BYTES]);
for (int64_t i = 0; i < f.entry_count(); ++i) {
const RadFileEntry& e = f.entry(i);
for (uint32_t k = 0; k < e.n_planes; ++k) {
const RadFilePlane& p = f.plane(e, (int)k);
add(p.offset, p.bytes);
}
}
std::sort(live.begin(), live.end());
const uint64_t end = (uint64_t)f.size();
uint64_t at = 0, total = 0, listed = 0;
int64_t n = 0;
auto gap = [&](uint64_t a, uint64_t b) {
if (b <= a) return;
total += b - a;
if ((int64_t)(b - a) < min_bytes) return;
std::printf("%llu %llu\n", (unsigned long long)a, (unsigned long long)(b - a));
listed += b - a;
++n;
};
for (const auto& r : live) {
gap(at, r.first < end ? r.first : end);
if (r.second > at) at = r.second;
}
gap(at, end);
std::fprintf(stderr, "rad-info: %s of %s is in no table and no plane; %lld range(s) of at "
"least %s hold %s\n", humanb((int64_t)total).c_str(),
humanb((int64_t)end).c_str(), (long long)n, humanb(min_bytes).c_str(),
humanb((int64_t)listed).c_str());
return 0;
}
/* ------------------------------------------------------------------ a weight's planes */
/* Where the planes of the weights `glob` names sit in the file: before an in-place run replaces
* or moves them, the list of bytes that run will leave behind. */
int print_planes(const RadFile& f, const std::string& glob) {
for (int64_t i = 0; i < f.entry_count(); ++i) {
const RadFileEntry& e = f.entry(i);
const char* name = f.str(e.name);
if (!rad::recipe_glob(glob.c_str(), name)) continue;
for (uint32_t k = 0; k < e.n_planes; ++k) {
const RadFilePlane& p = f.plane(e, (int)k);
std::printf("%llu %llu %s\n", (unsigned long long)p.offset,
(unsigned long long)p.bytes, name);
}
}
return 0;
}
} /* namespace */
int main(int argc, char** argv) {
@@ -404,6 +481,8 @@ int main(int argc, char** argv) {
bool verbose = false, only_meta = false, only_vocab = false, only_recipe = false, plugins = false;
std::string home = rad_home();
int top = 20;
int64_t unref_min = -1;
std::string planes_glob;
for (int i = 1; i < argc; ++i) {
std::string a = argv[i];
@@ -419,6 +498,12 @@ int main(int argc, char** argv) {
else if (a == "--profile") top = (int)rad_flag_int("rad-info", "--profile", next("--profile"),
0, INT32_MAX);
else if (a == "--recipe") only_recipe = true;
else if (a == "--unreferenced") {
unref_min = 1 << 20;
if (i + 1 < argc && argv[i + 1][0] >= '0' && argv[i + 1][0] <= '9')
unref_min = rad_flag_int("rad-info", "--unreferenced", argv[++i], 1, INT64_MAX);
}
else if (a == "--planes") planes_glob = next("--planes");
else if (a == "--plugins") plugins = true;
else if (a == "--home") home = next("--home");
else if (!a.empty() && a[0] == '-') {
@@ -439,6 +524,8 @@ int main(int argc, char** argv) {
std::fputs(r[0] ? r : "# no recipe: every weight is the checkpoint's own\n", stdout);
return 0;
}
if (unref_min >= 0) return print_unreferenced(f, unref_min);
if (!planes_glob.empty()) return print_planes(f, planes_glob);
if (only_meta) { print_meta(f); return 0; }
if (only_vocab) { print_vocab(f); return 0; }
+22 -8
View File
@@ -1588,8 +1588,13 @@ void Replay::run_one(size_t fi, const KfCase& c, const RadOpSchema* schema,
}
}
int s, sync = RAD_OK;
{
/* A row with per-instance state is set up as the engine sets it up (one rank here) and
* torn down once the launch has drained. */
void* inst = nullptr;
int s = row->info->init ? row->info->init(a.p, a.n_p, 0, 1, &inst) : RAD_OK;
int sync = RAD_OK;
if (s >= 0) {
a.instance = inst;
const auto l0 = std::chrono::steady_clock::now();
s = row->info->launch(&a, dom == RAD_DOMAIN_DEVICE ? stream : nullptr);
sync = (s >= 0 && dom == RAD_DOMAIN_DEVICE) ? rad_stream_sync(stream) : RAD_OK;
@@ -1599,6 +1604,7 @@ void Replay::run_one(size_t fi, const KfCase& c, const RadOpSchema* schema,
ph_.launch_by_lib[lib] += sec;
checked_s = sec;
}
if (row->info->init && row->info->fini) row->info->fini(inst);
if (s < 0 || sync < 0) {
/* A kernel refusing a geometry its own constraints accepted is a bug in the row
* (spec §17). */
@@ -2280,7 +2286,7 @@ void usage() {
" --report FILE write the markdown report: a summary of every loaded library, the\n"
" op-by-library completeness matrix, every case and its error, the\n"
" speed table, and every skip named\n"
" --kv-cache-dtype T bf16 | fp8, the cache width declare is run at, as it is on the\n"
" --kv-cache-dtype T bf16 | i8, the cache width declare is run at, as it is on the\n"
" engine: an architecture whose attention kernels serve only one width\n"
" declares no attention at the other. Default bf16\n"
" --num-speculative-tokens N\n"
@@ -2366,9 +2372,9 @@ int main(int argc, char** argv) {
else if (a == "--mm-max-patches") mm_max_patches = std::atoll(next("--mm-max-patches"));
else if (a == "--kv-cache-dtype") {
const std::string v = next("--kv-cache-dtype");
if (v == "fp8") kv_dtype = RAD_F8E4M3;
if (v == "i8") kv_dtype = RAD_I8;
else if (v != "bf16") { std::fprintf(stderr, "rad-kbench: --kv-cache-dtype takes bf16 "
"or fp8, not '%s'\n", v.c_str());
"or i8, not '%s'\n", v.c_str());
return 2; }
}
else if (a == "--record") record_path = next("--record");
@@ -3195,9 +3201,17 @@ int main(int argc, char** argv) {
a.scratch_bytes = need;
}
}
const int s = row->info->launch(&a, stream);
if (s < 0) return s;
return rad_stream_sync(stream);
/* Per-instance state, as the replay sets it up (one rank). */
void* inst = nullptr;
if (row->info->init) {
const int is = row->info->init(a.p, a.n_p, 0, 1, &inst);
if (is < 0) return is;
a.instance = inst;
}
int s = row->info->launch(&a, stream);
if (s >= 0) s = rad_stream_sync(stream);
if (row->info->init && row->info->fini) row->info->fini(inst);
return s;
};
/* The oracle's launch counts toward its library's share of the launch phase. */
+4 -4
View File
@@ -48,7 +48,7 @@ void usage() {
" --max-seqs N the max_seqs declare is run at (default 256)\n"
" --tp N tensor-parallel width to declare at (default 1). The shapes a\n"
" sharded deployment runs are not the shapes tp=1 runs.\n"
" --kv-cache-dtype T bf16 (default) or fp8 -- attention bands are gated on it.\n"
" --kv-cache-dtype T bf16 (default) or i8 -- attention bands are gated on it.\n"
" Declare what the served engine runs, or the tune rows will not\n"
" match the bands it selects.\n"
" --tp-wire MODE exact (default) or wht6 -- selects the all-reduce family.\n"
@@ -333,7 +333,7 @@ int main(int argc, char** argv) {
int64_t max_tok = 8192;
int64_t max_seqs = 256;
int tp = 1, spec = -1; /* -1 = the container's own drafter depth */
int kv_dtype = RAD_DT_INVALID; /* RAD_F8E4M3 = the engine's --kv-cache-dtype fp8 */
int kv_dtype = RAD_DT_INVALID; /* RAD_I8 = the engine's --kv-cache-dtype i8 */
int wire_lossy = 0; /* the engine's --tp-wire wht6 */
int64_t wire_min_kb = 128; /* the engine's --tp-wire-min-kb */
bool dry = false, verbose = false;
@@ -361,10 +361,10 @@ int main(int argc, char** argv) {
else if (a == "--tp") tp = (int)num("--tp", 1, INT32_MAX);
else if (a == "--kv-cache-dtype") {
const char* v = next("--kv-cache-dtype");
if (!std::strcmp(v, "fp8")) kv_dtype = RAD_F8E4M3;
if (!std::strcmp(v, "i8")) kv_dtype = RAD_I8;
else if (!std::strcmp(v, "bf16")) kv_dtype = RAD_DT_INVALID;
else { std::fprintf(stderr, "rad-tune: --kv-cache-dtype: '%s' is not one of "
"bf16, fp8 (the tuner tunes the bands it declares; other "
"bf16, i8 (the tuner tunes the bands it declares; other "
"encodings are the engine's)\n", v); return 2; }
}
else if (a == "--tp-wire") {
+41
View File
@@ -0,0 +1,41 @@
/* rad-yaml -- a radiance command line written as the YAML file `radiance --config` reads
* (core/fleet/config.h, docs/MULTIMODEL.md §4).
*
* rad-yaml --model /models/q.rad --tp 2 --port 8000 > radiance.yaml
* radiance --config radiance.yaml
*
* The flags are parsed by the engine's own parser first, so a line the server would have refused is
* refused here with the same message. The file is then loaded back before it is printed, so what
* comes out is a file the server accepts.
*/
#include "rad_core.h"
#include "fleet/config.h"
#include <cstdio>
#include <string>
#include <vector>
static const char kUsage[] = "usage: rad-yaml FLAGS... print the YAML file these radiance flags configure\n";
int main(int argc, char** argv) {
if (argc < 2) {
fputs(kUsage, stderr);
return 2;
}
rad::Config flags;
const int s = rad::config_parse(argc, argv, &flags);
if (s == 1) {
fputs(kUsage, stderr);
return 0;
}
if (s < 0) return 2;
const std::string y = rad::fleet::yaml_from_args(argc, argv);
rad::fleet::FleetConfig fc;
if (rad::fleet::parse(y, "rad-yaml output", &fc) != RAD_OK) {
fprintf(stderr, "rad-yaml: the file below does not load; please report this command line\n%s", y.c_str());
return 1;
}
fputs(y.c_str(), stdout);
return 0;
}