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

Conflicts, both sides kept:
- abi: RAD_ABI_VERSION 37 (upstream); the fork's RadBuildCtx.plain_norm after upstream's
  expert_file_tier, widened to int64_t so it starts past ABI 37's 208-byte struct instead of in
  its tail padding (abi_layout_test); RadSyclStream rows after RadShapeGen*.
- arch/common/rad_block_gdn_fp8.h: upstream's q8_rot guard and the fork's o_plain guard
  combined; the decode-row q_o.step only where q_o is declared (!o_plain).
- docs/OPS.md: upstream's optional params on sample_logprobs, the fork's q_temp on
  mtp_couple_propose.

Also ignores /baseline-models/ (local model copies).

Host tests: arch_test's MTP lint/graph-pin failures are unchanged from before the merge (the
fork's mtp.fc LinearFP8, 10a99a5); avx_check's hand-built moe_gemm_q w4a8 case also fails on
upstream's own files; images/videos need FFmpeg; three binaries over their CPU budget on this VM.
SYCL card tests 3/3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-11-07 22:13:08 +01:00
commit 45f3b510c7
365 files changed
+56942 -6331

No files matched your search

+47 -6
View File
@@ -678,6 +678,19 @@ uint64_t kf_weight_seed(const KfOperand& d, size_t k) {
return rad_splitmix(s);
}
KfOperand kf_table_entry(const KfOperand& d) {
KfOperand one = d;
one.role = RAD_OPD_WEIGHT;
if (!d.shape.empty()) one.shape.assign(d.shape.begin() + 1, d.shape.end());
return one;
}
void kf_draw_entry_planes(const KfOperand& d, size_t k, int64_t e,
std::vector<std::vector<uint8_t>>* out) {
uint64_t es = kf_weight_seed(d, k) ^ (0xC2B2AE3D27D4EB4Full * (uint64_t)(e + 1));
kf_draw_planes(kf_table_entry(d), rad_splitmix(es), out);
}
int kf_draw_table(const KfOperand& d, size_t k, std::vector<uint8_t>* out, std::string* why) {
out->clear();
if (!d.has_enc || d.shape.size() < 2 || d.shape[0] <= 0) {
@@ -686,21 +699,17 @@ int kf_draw_table(const KfOperand& d, size_t k, std::vector<uint8_t>* out, std::
}
const int64_t ne = d.shape[0];
/* One expert: the table's selection over its shape without the leading dimension. */
KfOperand one = d;
one.role = RAD_OPD_WEIGHT;
one.shape.assign(d.shape.begin() + 1, d.shape.end());
const KfOperand one = kf_table_entry(d);
const int64_t per = rad_dtype_bytes(d.dtype, rad_numel(one.shape));
if (per <= 0) {
if (why) *why = "a dtype the core cannot size";
return RAD_E_DTYPE;
}
out->assign((size_t)(per * ne), 0);
const uint64_t base = kf_weight_seed(d, k);
std::vector<std::vector<uint8_t>> pl;
std::vector<uint8_t> logical;
for (int64_t e = 0; e < ne; ++e) {
uint64_t es = base ^ (0xC2B2AE3D27D4EB4Full * (uint64_t)(e + 1));
kf_draw_planes(one, rad_splitmix(es), &pl);
kf_draw_entry_planes(d, k, e, &pl);
std::string w;
const int rc = kf_planes_logical(one, pl, &logical, &w);
if (rc != RAD_OK || (int64_t)logical.size() != per) {
@@ -714,6 +723,38 @@ int kf_draw_table(const KfOperand& d, size_t k, std::vector<uint8_t>* out, std::
return RAD_OK;
}
int kf_lay_table(const RadKernelInfo* info, const RadParam* p, int n_p, int operand,
const KfOperand& d, const KfEntryPlanes& planes, RadLayout* lay,
std::vector<uint8_t>* out) {
out->clear();
if (!info || !info->layout || !d.has_enc) return RAD_E_UNSUPPORTED;
if (d.shape.size() < 2 || d.shape[0] <= 0) return RAD_E_SHAPE;
const KfOperand one = kf_table_entry(d);
std::vector<std::vector<uint8_t>> pl;
std::vector<uint8_t> laid;
for (int64_t e = 0; e < d.shape[0]; ++e) {
int rc = planes(e, &pl);
if (rc != RAD_OK) return rc;
RadLayout le{};
rc = kf_lay_weight(info, p, n_p, operand, one, pl, &le, &laid);
if (rc != RAD_OK) return rc;
if (e == 0) {
/* The kernel strides a stacked table by the declared entry in the stored dtype, so a
* layout that changes an entry's size (an fp8 lm_head's appended scales) cannot be
* stacked. A plugin-private dtype has no size the core knows; its kernel reads the
* entry it laid out. */
const int64_t declared = rad_dtype_bytes(le.dtype, rad_numel(one.shape));
if (declared > 0 && declared != le.bytes) return RAD_E_SHAPE;
*lay = le;
out->reserve((size_t)(le.bytes * d.shape[0]));
} else if (le.bytes != lay->bytes || le.dtype != lay->dtype) {
return RAD_E_SHAPE;
}
out->insert(out->end(), laid.begin(), laid.end());
}
return RAD_OK;
}
void kf_operand_enc(const WeightInfo& w, KfOperand* d) {
d->has_enc = true;
d->enc = w.enc;
+22
View File
@@ -23,6 +23,7 @@
#include "rad_core.h"
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
@@ -189,6 +190,27 @@ uint64_t kf_weight_seed(const KfOperand& d, size_t k);
* refusal with `why`. */
int kf_draw_table(const KfOperand& d, size_t k, std::vector<uint8_t>* out, std::string* why);
/* One entry of a weight table: the table's encoding and selection over its shape without the
* leading expert dimension, as a weight operand. */
KfOperand kf_table_entry(const KfOperand& d);
/* Entry e's planes as kf_draw_table draws them. */
void kf_draw_entry_planes(const KfOperand& d, size_t k, int64_t e,
std::vector<std::vector<uint8_t>>* out);
/* Entry e's selected planes, from the fixture's draw or a container. RAD_OK, or the refusal. */
using KfEntryPlanes = std::function<int(int64_t e, std::vector<std::vector<uint8_t>>* out)>;
/* The bytes kernel `info` reads for the weight table `operand`: every entry laid out from its
* planes as kf_lay_weight lays out a weight, stacked one laid entry apart, which is how a kernel
* reads a table it is handed whole rather than through the engine's pointers. `lay` is the first
* entry's. Returns kf_lay_weight's answer for the entries: RAD_E_UNSUPPORTED when the kernel reads
* them as decoded (kf_draw_table's bytes); RAD_E_SHAPE when the entries lay out to different
* sizes, or to a size the declared entry does not stride by. */
int kf_lay_table(const RadKernelInfo* info, const RadParam* p, int n_p, int operand,
const KfOperand& d, const KfEntryPlanes& planes, RadLayout* lay,
std::vector<uint8_t>* out);
/* ================================================================== drawing an input
*
* One implementation for recorder and reader, which must produce byte-identical inputs. An index
+4 -2
View File
@@ -37,6 +37,8 @@ function t_opd(t, q,w,io) {
if (sub(/:inout$/, "", t)) io = ":inout"
sub(/:(in|out)$/, "", t); return t w io q }
# ---- doc notation: `name` followed by its annotations -------------------------------------
# POSIX awk only: mawk, Debian's and Ubuntu's default awk, has no gensub.
function trim(t) { sub(/^ +/, "", t); sub(/ +$/, "", t); return t }
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) {
@@ -63,9 +65,9 @@ FILENAME != doc {
# ---- the doc rows --------------------------------------------------------------------------
/^\| `/ {
n = split($0, c, "|")
op = d_name(gensub(/^ +| +$/, "", "g", c[2])); documented[op] = 1
op = d_name(trim(c[2])); documented[op] = 1
if (n > 5) { exempt++; printf "exempt %-24s line %d -- %s\n", op, FNR,
gensub(/^ +| +$/, "", "g", c[5]); next }
trim(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 }
+7 -2
View File
@@ -20,7 +20,7 @@ does, so rank w-1 carries them.
bf16 is handled as raw u16 (no arithmetic happens here), so numpy alone suffices.
"""
import argparse, json, os, re, shutil, struct, sys
import argparse, json, os, re, shutil, struct, subprocess, sys
import numpy as np
DT = {"BF16": (np.uint16, 2), "F16": (np.float16, 2), "F32": (np.float32, 4), "I64": (np.int64, 8),
@@ -111,6 +111,10 @@ def main():
os.makedirs(a.dst, exist_ok=True)
idx_path = os.path.join(a.src, "model.safetensors.index.json")
files = sorted(set(json.load(open(idx_path))["weight_map"].values())) if os.path.exists(idx_path) else ["model.safetensors"]
# Shard names come from the checkpoint's own index: each must be a bare file name in it.
for fn in files:
if not isinstance(fn, str) or not fn or fn != os.path.basename(fn) or fn in (".", ".."):
sys.exit(f"{idx_path}: shard name {fn!r} is not a file name in the checkpoint directory")
def parts(w_, sizes, news, axis=0):
"""pad each consecutive segment of `sizes` along `axis` to `news` (zeros after the real rows)."""
@@ -170,7 +174,8 @@ def main():
if a.sparse:
dstf = os.path.join(a.dst, fn)
if not os.path.exists(dstf):
r = os.system(f"cp --reflink=always '{os.path.join(a.src, fn)}' '{dstf}' 2>/dev/null") or 0
r = subprocess.run(["cp", "--reflink=always", os.path.join(a.src, fn), dstf],
stderr=subprocess.DEVNULL).returncode
if r: os.link(os.path.join(a.src, fn), dstf) # not btrfs/xfs: hard link, still no copy
else:
st_write_stream(os.path.join(a.dst, fn), meta, items); print(f" wrote {fn} ({len(items)} tensors)", flush=True)
+27
View File
@@ -1005,6 +1005,30 @@ int main(int argc, char** argv) {
if (L.declared && L.status == RAD_OK) plan.push_back(&L);
std::sort(plan.begin(), plan.end(), plan_less);
/* The checkpoint tensors no planned weight reads. Only declared weights are written, so a
* tower or head the plugin does not recognise is left out without an error; this says so. A
* tensor beside a read one (`X.weight_scale` beside `X.weight`) counts as read. */
{
auto stem = [](const std::string& n) { return n.substr(0, n.rfind('.')); };
std::unordered_set<std::string> read, stems;
for (const RadNameMap& nm : prog.name_map) {
const auto it = nm.declared ? logical.find(nm.declared) : logical.end();
if (it == logical.end() || !it->second.declared || it->second.status != RAD_OK) continue;
for (int k = 0; k < nm.n_src; ++k)
if (nm.src[k]) { read.insert(nm.src[k]); stems.insert(stem(nm.src[k])); }
}
std::vector<std::string> unread;
for (const SrcTensor& t : ck.tensors())
if (!read.count(t.name) && !stems.count(stem(t.name))) unread.push_back(t.name);
if (!unread.empty()) {
std::string list;
for (size_t i = 0; i < unread.size() && i < 8; ++i) list += (i ? ", " : "") + unread[i];
RAD_WARN("%zu of %zu checkpoint tensors are read by no declared weight and are not "
"written: %s%s", unread.size(), ck.tensors().size(), list.c_str(),
unread.size() > 8 ? ", ..." : "");
}
}
{
int64_t n_q = 0, n_kept = 0, n_imp = 0;
for (const Logical* L : plan) (L->rule ? n_q : L->src.imported ? n_imp : n_kept)++;
@@ -1253,6 +1277,9 @@ int main(int argc, char** argv) {
w.abort();
return 1;
}
} else if (meta_textless(ck.meta().get("radiance.text"))) {
RAD_INFO("vocab none: the model reads no text");
vocab_textless(vb);
} else if (file_exists(ck.tok_dir() + "/tokenizer.json")) {
const std::string tj = ck.tok_dir() + "/tokenizer.json";
RAD_INFO("vocab %s", tj.c_str());
+94 -9
View File
@@ -983,6 +983,8 @@ private:
const std::vector<Drawn>& in, uint64_t input_hash, const Run& run);
bool lay_out(const KfCase& c, size_t k, const RadOpSchema* schema, const Run& run,
const Drawn& d, Bytes* laid, RadTensor* desc);
bool lay_out_table(const KfCase& c, size_t k, const RadOpSchema* schema, const Run& run,
Bytes* laid, RadTensor* desc);
int record_case(const KfCase& base, KfCase* out, std::string* why);
int rerecord();
int record_rows();
@@ -1364,7 +1366,8 @@ static bool lays_out_weight(const KernelRow* row, const Geometry& g, const KfCas
if (!info || !info->layout) return false;
for (size_t k = 0; k < c.opd.size(); ++k) {
const KfOperand& d = c.opd[k];
if (d.absent || d.role != RAD_OPD_WEIGHT || !d.has_enc) continue;
if (d.absent || (d.role != RAD_OPD_WEIGHT && d.role != RAD_OPD_WTAB) || !d.has_enc)
continue;
RadTensor pt[RAD_ENC_MAX_PLANES];
const int n = (int)d.sel.size();
if (n < 1 || n > RAD_ENC_MAX_PLANES) continue;
@@ -1407,6 +1410,34 @@ bool Replay::lay_out(const KfCase& c, size_t k, const RadOpSchema* schema, const
return true;
}
/* The same for a weight table whose kernel lays out each expert: the experts' planes as the draw
* made them (kf_draw_entry_planes), each laid out, stacked. `laid` empty: the row reads the table
* as decoded. */
bool Replay::lay_out_table(const KfCase& c, size_t k, const RadOpSchema* schema, const Run& run,
Bytes* laid, RadTensor* desc) {
PhaseTimer pt(&ph_, kb::PH_LAYOUT);
laid->clear();
const KfOperand& d = c.opd[k];
if (!d.has_enc || d.undrawn) return true;
RadLayout lay{};
const int lrc = kf_lay_table(run.row->info, run.g.params(), run.g.n_params(), (int)k, d,
[&](int64_t e, std::vector<Bytes>* pl) {
kf_draw_entry_planes(d, k, e, pl);
return (int)RAD_OK;
},
&lay, laid);
if (lrc == RAD_E_UNSUPPORTED) { laid->clear(); return true; }
if (lrc < 0) {
const char* opd_name = schema->operands[k].name ? schema->operands[k].name : "?";
nm_.skipped[c.op + " (" + run.lib + "/" + run.row->info->name + " cannot lay out the " +
"table '" + opd_name + "' from " + enc_name(d.enc) + ": " +
rad_strerror(lrc) + ")"]++;
return false;
}
kf_describe_laid(d, lay, laid->data(), desc);
return true;
}
void Replay::run_one(size_t fi, const KfCase& c, const RadOpSchema* schema,
const std::vector<Drawn>& in, uint64_t input_hash, const Run& run) {
const size_t n_opd = c.opd.size();
@@ -1504,11 +1535,18 @@ void Replay::run_one(size_t fi, const KfCase& c, const RadOpSchema* schema,
}
continue;
}
if (!guarded_alloc(dev[k], (int64_t)src.size(), stream)) {
Bytes laid;
if (c.opd[k].role == RAD_OPD_WTAB &&
!lay_out_table(c, k, schema, run, &laid, &t[k])) {
++st_.skipped; release(); return;
}
const Bytes& up = laid.empty() ? src : laid;
if (!guarded_alloc(dev[k], (int64_t)up.size(), stream)) {
nm_.skipped[c.op + " (no device memory for this case)"]++;
++st_.skipped; release(); return;
}
if (rad_memcpy_async(dev[k].p, src.data(), dev[k].bytes, stream) < 0) {
if (rad_memcpy_async(dev[k].p, up.data(), dev[k].bytes, stream) < 0 ||
(!laid.empty() && rad_stream_sync(stream) < 0)) {
++st_.skipped; release(); return;
}
t[k].data = dev[k].p;
@@ -1518,11 +1556,12 @@ void Replay::run_one(size_t fi, const KfCase& c, const RadOpSchema* schema,
/* Host: weights laid out in place, written operands copied, inputs shared. */
for (size_t k = 0; k < n_opd; ++k) {
if (c.opd[k].absent || !in[k].bytes) continue;
if (c.opd[k].role == RAD_OPD_WEIGHT) {
if (c.opd[k].role == RAD_OPD_WEIGHT || c.opd[k].role == RAD_OPD_WTAB) {
Bytes laid;
if (!lay_out(c, k, schema, run, in[k], &laid, &t[k])) {
++st_.skipped; return;
}
const bool ok = c.opd[k].role == RAD_OPD_WEIGHT
? lay_out(c, k, schema, run, in[k], &laid, &t[k])
: lay_out_table(c, k, schema, run, &laid, &t[k]);
if (!ok) { ++st_.skipped; return; }
if (!laid.empty()) { own[k].swap(laid); t[k].data = own[k].data(); }
continue;
}
@@ -2345,9 +2384,12 @@ int main(int argc, char** argv) {
else if (a == "--coverage") ro.coverage_dir = next("--coverage");
else if (a == "--coverage-write") ro.coverage_write = true;
else if (a == "--analysis") analysis_path = next("--analysis");
else if (a == "--max-cases") max_cases = std::atoi(next("--max-cases"));
else if (a == "--max-cases")
max_cases = (int)rad_flag_int("rad-kbench", "--max-cases", next("--max-cases"), 0,
INT32_MAX);
else if (a == "--max-bytes")
max_case_bytes = (int64_t)std::atoll(next("--max-bytes")) << 20;
max_case_bytes = rad_flag_int("rad-kbench", "--max-bytes", next("--max-bytes"), 1,
INT32_MAX) << 20;
else if (a == "--no-fusion") fuse_check = false;
else if (a == "--bench") bench = true;
else if (a == "--timing-only") timing_only = true;
@@ -3017,6 +3059,49 @@ int main(int argc, char** argv) {
}
if (read) from_container = true;
else kf_draw(kop, k, M, kf_vocab_rows(kop), 0, &bufs[k]);
/* A kernel that lays its experts out (libr4d's 4-bit ones) reads each
* expert's arrangement of the same planes, stacked; the oracle reads the
* table they decode to. */
if (kop[k].has_enc && !kop[k].undrawn) {
const char* opd_name = o.schema->operands[k].name
? o.schema->operands[k].name : "?";
auto planes = [&](int64_t e, std::vector<std::vector<uint8_t>>* pl) {
if (!read) {
kf_draw_entry_planes(kop[k], k, e, pl);
return (int)RAD_OK;
}
const WeightInfo& wi = prog.weights[run[(size_t)e]];
const RadFileEntry* fe = f.find(wi.source);
if (!fe) return (int)RAD_E_NOTFOUND;
pl->clear();
for (int j = 0; j < wi.n_sel; ++j) {
const RadFilePlane& fp = f.plane(*fe, wi.sel[j]);
const uint8_t* src = (const uint8_t*)f.data(fp);
pl->emplace_back(src, src + fp.bytes);
}
return (int)RAD_OK;
};
RadLayout lay{};
std::vector<uint8_t> laid;
const int lrc = kf_lay_table(r.row->info, g.params(), g.n_params(),
(int)k, kop[k], planes, &lay, &laid);
if (lrc == RAD_OK) {
ref_out[k] = bufs[k];
t_ref[k] = mk(ref_out[k]);
bufs[k].swap(laid);
kf_describe_laid(kop[k], lay, bufs[k].data(), &t_test[k]);
continue;
}
if (lrc != RAD_E_UNSUPPORTED) {
skipped_ops[o.op + " (" + std::string(r.row->info->name) +
" cannot lay out the table '" + opd_name +
"' from " +
enc_name(kop[k].enc) + ": " + rad_strerror(lrc) +
")"]++;
unusable = true;
break;
}
}
} else if (role == RAD_OPD_IN || role == RAD_OPD_INOUT) {
/* The fixture's draw, the single implementation recorder and replay
* share. */
+9
View File
@@ -9,6 +9,7 @@
* rad-schemas libr4d.so libref.so diff them, in hierarchy order
*/
#include "rad_abi.h"
#include "rad_abi_layout.h"
#include <dlfcn.h>
#include <cstdio>
@@ -72,6 +73,14 @@ int load(const char* path, Loaded* out) {
fprintf(stderr, "%s: ABI %u, this build is %u\n", path, abi(), RAD_ABI_VERSION);
return -1;
}
/* One version can name two layouts; the engine refuses a mismatched fingerprint, and so does
* this tool, which reads the same structs. */
auto layout = (uint64_t (*)(void))dlsym(out->h, "rad_plugin_abi_layout");
if (!layout || layout() != rad_abi_layout()) {
fprintf(stderr, "%s: built against another layout of ABI %u, or exports no "
"rad_plugin_abi_layout\n", path, 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);
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""vhead.py -- a vocabulary-weighted lm_head checkpoint, as the IQR-V4 recipes convert it.
vhead.py SRC DST CLASSES
SRC is a Hugging Face checkpoint directory (Qwen/Qwen3.8-27B), CLASSES a width-class file from
data/vhead/ (q38-27b-vhead-4.0.cls, -4.5, -5.0: the head's mean code width). DST becomes SRC with
lm_head.weight replaced by its width classes; every other file of SRC is linked, not copied. Pass DST
to rad-convert in place of SRC.
A vocabulary-weighted head stores each vocabulary row on one of four trellis widths, the tokens that
carry the most probability on the widest. The classes were chosen per 256-row run to minimise each
row's output error weighted by its token's mean probability on calibration text, at the file's mean
width; every TP2 rank's half of the vocabulary holds the same number of rows of each class, so the
class tensors shard by rows with the vocabulary. DST/vhead.safetensors holds, for each width B:
lm_head.kB.weight [rows, n_embd] bf16 the class's rows of lm_head.weight
lm_head.kB.ids [rows, 1] i32 each row's vocabulary id
rows in ascending id within each half of the vocabulary, and lm_head.vrow [n_vocab, 1] i32: an id's
width in the top four bits and its row in the class tensor below. rad-convert names the classes
output.kB; a recipe quantises each on its own width, and GPTQ reads the head's input Hessian for all
of them (libquant pools output.kB to output).
CLASSES: one ASCII line `radiance-vhead-1 n_vocab=V widths=a,b,c,d`, then V/4 bytes, an id's class
(the index of its width in `widths`) two bits each, id 4i in the low bits of byte i.
bf16 is moved as raw u16 (no arithmetic happens here), so numpy alone suffices.
"""
import json
import os
import struct
import sys
import numpy as np
def st_header(path):
with open(path, "rb") as f:
n = struct.unpack("<Q", f.read(8))[0]
return json.loads(f.read(n)), 8 + n
def st_tensor(path, name):
"""One tensor of a safetensors file as raw bytes viewed as u16 (bf16) or i32, shaped."""
hdr, base = st_header(path)
m = hdr[name]
dt = {"BF16": np.uint16, "F16": np.uint16, "I32": np.int32}[m["dtype"]]
a, b = m["data_offsets"]
return np.fromfile(path, dtype=dt, count=(b - a) // np.dtype(dt).itemsize,
offset=base + a).reshape(m["shape"]), m["dtype"]
def st_write(path, tensors):
"""tensors: [(name, array, dtype string)], written in that order, 8-byte aligned header."""
hdr, off = {}, 0
for name, a, dt in tensors:
hdr[name] = {"dtype": dt, "shape": list(a.shape), "data_offsets": [off, off + a.nbytes]}
off += a.nbytes
h = json.dumps(hdr, separators=(",", ":")).encode()
h += b" " * (-len(h) % 8)
with open(path, "wb") as f:
f.write(struct.pack("<Q", len(h)))
f.write(h)
for _, a, _ in tensors:
f.write(np.ascontiguousarray(a).tobytes())
def read_classes(path):
with open(path, "rb") as f:
head = f.readline().decode().split()
if not head or head[0] != "radiance-vhead-1":
raise SystemExit(f"vhead.py: {path} is not a radiance-vhead-1 class file")
kv = dict(t.split("=", 1) for t in head[1:])
V, widths = int(kv["n_vocab"]), [int(w) for w in kv["widths"].split(",")]
packed = np.frombuffer(f.read(), dtype=np.uint8)
if packed.size != (V + 3) // 4:
raise SystemExit(f"vhead.py: {path} holds {packed.size} bytes, {(V + 3) // 4} expected")
cls = np.stack([(packed >> (2 * j)) & 3 for j in range(4)], 1).reshape(-1)[:V]
return cls.astype(np.int64), widths
def main():
if len(sys.argv) != 4:
raise SystemExit(__doc__.split("\n\n")[1])
src, dst, cpath = sys.argv[1:4]
cls, widths = read_classes(cpath)
idx = json.load(open(os.path.join(src, "model.safetensors.index.json")))
W, dt = st_tensor(os.path.join(src, idx["weight_map"]["lm_head.weight"]), "lm_head.weight")
V = W.shape[0]
if cls.size != V or V % 2:
raise SystemExit(f"vhead.py: the class file covers {cls.size} ids, the head has {V} rows")
half = V // 2
ids = np.arange(V, dtype=np.int64)
vrow = np.full((V, 1), -1, dtype=np.int32)
out_ids, out_w = [], []
for i, k in enumerate(widths):
rows = np.concatenate([ids[:half][cls[:half] == i], ids[half:][cls[half:] == i]])
vrow[rows, 0] = (k << 28) | np.arange(rows.size, dtype=np.int32)
out_ids.append((f"lm_head.k{k}.ids", rows.astype(np.int32)[:, None], "I32"))
out_w.append((f"lm_head.k{k}.weight", W[rows], dt))
assert (vrow >= 0).all()
os.makedirs(dst, exist_ok=True)
st_write(os.path.join(dst, "vhead.safetensors"), out_ids + [("lm_head.vrow", vrow, "I32")] + out_w)
wm = dict(idx["weight_map"])
del wm["lm_head.weight"]
for name, _, _ in out_ids + out_w + [("lm_head.vrow", None, None)]:
wm[name] = "vhead.safetensors"
with open(os.path.join(dst, "model.safetensors.index.json"), "w") as f:
json.dump({"metadata": idx.get("metadata", {}), "weight_map": wm}, f)
# every other file of SRC, and every shard (lm_head's own shard still holds other tensors)
keep = set(idx["weight_map"].values())
for f in os.listdir(src):
if f == "model.safetensors.index.json" or (f.endswith(".safetensors") and f not in keep):
continue
if not os.path.lexists(os.path.join(dst, f)):
os.symlink(os.path.abspath(os.path.join(src, f)), os.path.join(dst, f))
print(f"vhead.py: {dst}: " + " ".join(f"k{k}:{int((cls == i).sum())}" for i, k in enumerate(widths))
+ f", mean {sum(widths[i] * int((cls == i).sum()) for i in range(len(widths))) / V:.3f} b")
if __name__ == "__main__":
main()