Archived
radiance 1.15.0
New models and formats: - IQR for Qwen3.8-27B: weights on the int8 grid under GPTQ, a trellis down each GPTQ column (IQR-V2), and IQR-V3, a computed trellis code under one scale a row, kept at its codes' width in VRAM and decoded in the GEMM; 15 IQR-V3 recipes from ~2 to ~7 bits a weight (data/recipes/q38-27b-*-v3.recipe, docs/IQR.md) - libhalo: a kernel library for Strix Halo (gfx1151), preferred there over libr3d - Nemotron 3.5 Embed 1B and 8B (nemotron35_embed): text and image embeddings through a Pixtral tower, on the card and on the CPU - Nemotron 3.5 Rerank 8B - /v1/systemone: Cloudflare's clef and clef-flash, Convai Innovations' Laya and Mica beside LiquidAI d1; scored steps read the candidates' logits from the head table with no lm_head pass - LFM2's 8-bit trunk: block-fp8 or int8 linears with the fused producers, and the d1-3B recipe - DeepSeek-V4.1's reply format with DSML tool calls and typed argument tags Weights on the drive: - The file tier reads only the experts the pass routes rows to; the draft head's weights stay in the host pool - A hot VRAM cache for routed experts read off the drive, reads deposited straight into free host pool slots, and copyless evictions; the file tier's counters are now ssd_* - GLM-5 Next shards its routed experts by expert, not by width, so they can live on the drive - The stall watch counts drive reads as progress, and the DMA lane's room check reads the lane's own completion fence Quantisation tooling: - --calib-corpus, --calib-dir and --calib-layers record each linear's input Hessian; beside --kld-record the reference's own run records them - --kld-top N records a sparse KL reference (the N most likely tokens and the tail's mass) - GPTQ in a third of the time with the same codes, trellis GPTQ on the card, vector codebooks with coordinate descent, and rad-convert --reuse repeated, each container supplying what the earlier ones lack Speculation: - Prompt lookup alone (--spec-ngram K, --spec-ngram-min/-max): each sequence keeps an index of its n-grams, and a proposal is verified only when its measured step cost says it pays; --draft-window adaptive follows it Speed: - IQR decode: the narrow tile splits K for four times the int8 tile's waves and folds each 128-K block once; at 8 tokens down and the output projections run in 0.61-0.82x and 0.70-0.92x FP8's time (2-6 bits); IQ6R-S-V3 with its DFlash2 drafter steps in 26.3 ms at TP2, against 29.4 ms before and FP8's 27.3 - Qwen MXFP4 feed-forward: the gated fold up to 16 rows, not 8 - libr4d: the gated prefill fold, the short-prompt split row, and the rows forms of rmsnorm and rope; KLATE again for the head-256 gqa6 paged prefill; gram_accum on the matrix cores Features: - /health, /v1/health and /ping answer 503 with "status": "stuck" once the device has advanced nothing for a minute or a queue has faulted, so a supervisor can restart a wedged server (#356) - --image-gen-max-pixels and --image-gen-max-refs size an image generator's buffers (#344) - The startup report lists only the options not at their default, with a count; -v lists all (#250) - --preempt-wait-ms bounds how long a preempted prefill waits for its whole-recompute room - --placement layer_offload spills dense layers so one --max-model-len sequence fits - Startup refuses amdgpu with CWSR off and says how to fix it; --proceed-with-incompatible-configuration starts anyway under an UNSUPPORTED banner Fixes: - The n-gram read-ahead hands each row to the reader once and reads only as far ahead as the row cache holds, and pauses while decode reads: about one drive read a row instead of two (#355) - A file-tier window reads each of its runs once, not once a run per run - The decode split law's verify floor is bounded by the batch's workgroups: max_seqs 256 no longer declares 64x the scratch (#342) - A prefetch DMA list's mark stays out of the signal pool until the engine has read it, and a prefill stage copies only the blocks its own tables name (#343) - The split-KV row sum is read with fetch-inactive (#328) - LFM2 on the host backend: libref and libavx serve the row-form ops it declares (#348) - The preempted-prefill gate skips a KV group that holds no blocks (#352) - Every request entry point bounded, gated and sanitised (JSON depth, invalid UTF-8, control bytes in the log, the dashboard's CSP, cross-origin browsers on the loopback-only routes); a prompt id outside the vocabulary refused at admission; --api-key "" refused at startup - The telemetry the HTTP thread reads is atomic - An RMS norm row no longer depends on how many rows its launch carries; prefill attention's rescale is decided by live rows only - A --kld-record prefill chunk that finishes no sequence gets its logits on a tied-head model - A kernel's lazily made counter block is zeroed outside the lock other ranks take (a TP2 first-step hang) Changes: Plugin ABI 32. Every plugin exports a layout fingerprint of the ABI structs and the loader refuses a plugin without it or with another (#302), so out-of-tree plugins must be rebuilt. Appended: RadBuildCtx calib_* and gen_max_*, RadArchProbe gen_max_*, RadBatch score_only and plugin_words, RadDeviceProps::unified, RadChatFormat arg_json_value_prefix.
This commit is contained in:
commit
9ed3ef7a7b
452 files changed
+167762
-1346
No files matched your search
+282
-71
@@ -27,7 +27,8 @@ using json = nlohmann::ordered_json;
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr const char* kFormat = "radiance-kld-1";
|
||||
constexpr const char* kFormat = "radiance-kld-1";
|
||||
constexpr const char* kFormatTop = "radiance-kld-top-1";
|
||||
|
||||
uint64_t fnv1a(const void* p, size_t n, uint64_t h = 1469598103934665603ull) {
|
||||
const auto* b = static_cast<const uint8_t*>(p);
|
||||
@@ -150,8 +151,93 @@ inline float logit_at(const std::vector<KldShard>& sh, int64_t at, int64_t id) {
|
||||
|
||||
struct TopEntry { int32_t id; float lp; };
|
||||
|
||||
/* The head's order: a min-heap on log p, so an entry leaves only for a strictly larger one and a
|
||||
* tie keeps the lower id, which is the candidate's argmax rule. */
|
||||
inline bool worse(const TopEntry& a, const TopEntry& b) {
|
||||
return a.lp > b.lp || (a.lp == b.lp && a.id < b.id);
|
||||
}
|
||||
|
||||
/* e^x for x <= 0 in f32, within 2 ulp: x = n ln 2 + r with |r| <= ln 2 / 2, Cephes's degree-6
|
||||
* polynomial in r, and 2^n through the exponent bits. Plain arithmetic, so the row loops below
|
||||
* vectorise; below -87.3 (where expf leaves the normal range) it returns 0. */
|
||||
#define RAD_KLD_EXP_BODY \
|
||||
const float xc = std::max(x, -87.3f); \
|
||||
const float n = std::floor(xc * 1.44269504088896341f + 0.5f); \
|
||||
const float r = xc - n * 0.693359375f + n * 2.12194440e-4f; \
|
||||
float y = 1.9875691500e-4f; \
|
||||
y = y * r + 1.3981999507e-3f; \
|
||||
y = y * r + 8.3334519073e-3f; \
|
||||
y = y * r + 4.1665795894e-2f; \
|
||||
y = y * r + 1.6666665459e-1f; \
|
||||
y = y * r + 5.0000001201e-1f; \
|
||||
y = y * r * r + r + 1.0f; \
|
||||
const int32_t bits = ((int32_t)n + 127) << 23; \
|
||||
float scale; \
|
||||
std::memcpy(&scale, &bits, 4); \
|
||||
return x < -87.3f ? 0.0f : y * scale;
|
||||
|
||||
inline float exp_le0(float x) { RAD_KLD_EXP_BODY }
|
||||
__attribute__((target("avx2,fma"), always_inline)) inline float exp_le0_avx2(float x) { RAD_KLD_EXP_BODY }
|
||||
#undef RAD_KLD_EXP_BODY
|
||||
|
||||
/* Sums over one shard's row of n logits, against the row's max m:
|
||||
* s = sum e^(l - m)
|
||||
* t = sum e^(l - m) (l - m) (the entropy is log S - T / S)
|
||||
* rest = the part of s from tokens below thr, or, with `mark`, from tokens it does not flag
|
||||
* eq = how many logits equal thr
|
||||
* in sixteen independent lanes, so the loop vectorises without reassociating a sum. */
|
||||
struct RowSums { double s = 0, t = 0, rest = 0; int64_t eq = 0; };
|
||||
|
||||
#define RAD_KLD_ROW_BODY(EXP) \
|
||||
constexpr int L = 16; \
|
||||
double s[L] = {}, t[L] = {}, rest[L] = {}; \
|
||||
int32_t eq[L] = {}; \
|
||||
int64_t i = 0; \
|
||||
for (; i + L <= n; i += L) \
|
||||
for (int k = 0; k < L; ++k) { \
|
||||
const float x = l[i + k] - m, e = EXP(x); \
|
||||
const bool out = mark ? !mark[i + k] : l[i + k] < thr; \
|
||||
s[k] += e; \
|
||||
t[k] += (double)(e * x); \
|
||||
rest[k] += out ? (double)e : 0.0; \
|
||||
eq[k] += l[i + k] == thr; \
|
||||
} \
|
||||
RowSums o; \
|
||||
for (; i < n; ++i) { \
|
||||
const float x = l[i] - m, e = EXP(x); \
|
||||
o.s += e; \
|
||||
o.t += (double)(e * x); \
|
||||
if (mark ? !mark[i] : l[i] < thr) o.rest += e; \
|
||||
o.eq += l[i] == thr; \
|
||||
} \
|
||||
for (int k = 0; k < L; ++k) { o.s += s[k]; o.t += t[k]; o.rest += rest[k]; o.eq += eq[k]; } \
|
||||
return o;
|
||||
|
||||
RowSums row_sums_base(const float* l, int64_t n, float m, float thr, const uint8_t* mark) {
|
||||
RAD_KLD_ROW_BODY(exp_le0)
|
||||
}
|
||||
__attribute__((target("avx2,fma")))
|
||||
RowSums row_sums_avx2(const float* l, int64_t n, float m, float thr, const uint8_t* mark) {
|
||||
RAD_KLD_ROW_BODY(exp_le0_avx2)
|
||||
}
|
||||
#undef RAD_KLD_ROW_BODY
|
||||
|
||||
RowSums row_sums(const float* l, int64_t n, float m, float thr, const uint8_t* mark) {
|
||||
static const bool avx2 = [] {
|
||||
__builtin_cpu_init();
|
||||
return __builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma");
|
||||
}();
|
||||
return avx2 ? row_sums_avx2(l, n, m, thr, mark) : row_sums_base(l, n, m, thr, mark);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
struct Kld::Scratch {
|
||||
std::vector<uint16_t> f16;
|
||||
std::vector<TopEntry> top;
|
||||
std::vector<uint8_t> mark;
|
||||
};
|
||||
|
||||
Kld::Kld() {
|
||||
for (uint32_t h = 0; h < 65536; ++h) f16_lut_[h] = rad_f16_to_f32((uint16_t)h);
|
||||
}
|
||||
@@ -168,8 +254,8 @@ std::vector<int32_t> Kld::tokens(size_t d) const {
|
||||
int Kld::open(const Config& cfg, std::shared_ptr<const Vocab> vocab, int64_t n_vocab,
|
||||
const std::string& model) {
|
||||
if (cfg.kld_record.empty()) return score_against(cfg.kld_ref, cfg.kld_out, n_vocab, model);
|
||||
RAD_TRY(load_corpus(cfg, vocab));
|
||||
return record_into(cfg.kld_record, n_vocab, model);
|
||||
RAD_TRY(load_corpus(cfg.kld_corpus, vocab));
|
||||
return record_into(cfg.kld_record, n_vocab, model, cfg.kld_top);
|
||||
}
|
||||
|
||||
int Kld::score_against(const std::string& dir, const std::string& out, int64_t n_vocab,
|
||||
@@ -208,10 +294,10 @@ int Kld::add_doc(const std::string& source, const std::vector<int32_t>& ids, int
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the corpus (record) */
|
||||
int Kld::load_corpus(const Config& cfg, const std::shared_ptr<const Vocab>& vocab) {
|
||||
corpus_ = cfg.kld_corpus;
|
||||
int Kld::load_corpus(const std::string& path, const std::shared_ptr<const Vocab>& vocab) {
|
||||
corpus_ = path;
|
||||
std::ifstream in(corpus_, std::ios::binary);
|
||||
if (!in) { RAD_ERR("kld: cannot read --kld-corpus %s", corpus_.c_str()); return RAD_E_IO; }
|
||||
if (!in) { RAD_ERR("kld: cannot read the corpus %s", corpus_.c_str()); return RAD_E_IO; }
|
||||
Tokenizer tok;
|
||||
RAD_TRY(tok.init(vocab));
|
||||
std::string line;
|
||||
@@ -246,12 +332,15 @@ int Kld::load_corpus(const Config& cfg, const std::shared_ptr<const Vocab>& voca
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Kld::record_into(const std::string& dir, int64_t n_vocab, const std::string& model) {
|
||||
int Kld::record_into(const std::string& dir, int64_t n_vocab, const std::string& model, int top) {
|
||||
record_ = true;
|
||||
dir_ = dir;
|
||||
model_ = model;
|
||||
n_vocab_ = n_vocab;
|
||||
if (docs_.empty()) return RAD_E_INVAL;
|
||||
sparse_ = top > 0;
|
||||
top_ = sparse_ ? top : kKldTop;
|
||||
rows_w_ = sparse_ ? 3 : 2;
|
||||
if (docs_.empty() || top < 0 || top > kKldTopMax || top_ > n_vocab_) return RAD_E_INVAL;
|
||||
size_rows();
|
||||
/* Never overwrite a reference; a directory without a manifest is an interrupted run and is
|
||||
* reused. */
|
||||
@@ -265,17 +354,21 @@ int Kld::record_into(const std::string& dir, int64_t n_vocab, const std::string&
|
||||
RAD_ERR("kld: cannot write %s/tokens.i32: %s", dir_.c_str(), std::strerror(errno));
|
||||
return RAD_E_IO;
|
||||
}
|
||||
fd_logp_ = create_sized(dir_ + "/logp.f16", n_rows_ * n_vocab_ * 2);
|
||||
fd_top_ = create_sized(dir_ + "/top.bin", n_rows_ * kKldTop * (int64_t)sizeof(TopEntry));
|
||||
fd_rows_ = create_sized(dir_ + "/rows.f32", n_rows_ * 2 * 4);
|
||||
if (fd_logp_ < 0 || fd_top_ < 0 || fd_rows_ < 0) {
|
||||
if (!sparse_) fd_logp_ = create_sized(dir_ + "/logp.f16", n_rows_ * n_vocab_ * 2);
|
||||
fd_top_ = create_sized(dir_ + "/top.bin", n_rows_ * top_ * (int64_t)sizeof(TopEntry));
|
||||
fd_rows_ = create_sized(dir_ + "/rows.f32", n_rows_ * rows_w_ * 4);
|
||||
if ((!sparse_ && fd_logp_ < 0) || fd_top_ < 0 || fd_rows_ < 0) {
|
||||
RAD_ERR("kld: cannot create the reference files in %s: %s", dir_.c_str(),
|
||||
std::strerror(errno));
|
||||
return RAD_E_IO;
|
||||
}
|
||||
RAD_INFO("kld: recording %lld positions over %zu documents (%zu tokens) into %s, %.1f GiB",
|
||||
const int64_t bytes = (sparse_ ? 0 : n_rows_ * n_vocab_ * 2) +
|
||||
n_rows_ * (top_ * (int64_t)sizeof(TopEntry) + rows_w_ * 4);
|
||||
RAD_INFO("kld: recording %lld positions over %zu documents (%zu tokens) into %s, %s, %.1f GiB",
|
||||
(long long)n_rows_, docs_.size(), tokens_.size(), dir_.c_str(),
|
||||
(double)(n_rows_ * n_vocab_ * 2) / (1024.0 * 1024.0 * 1024.0));
|
||||
sparse_ ? fmt("the %d most likely tokens and the tail's mass", top_).c_str()
|
||||
: "the whole vocabulary",
|
||||
(double)bytes / (1024.0 * 1024.0 * 1024.0));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -293,11 +386,20 @@ int Kld::load_ref(const std::string& dir) {
|
||||
RAD_ERR("kld: %s/kld.json: %s", dir.c_str(), e.what());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if (m.value("format", std::string()) != kFormat) {
|
||||
RAD_ERR("kld: %s/kld.json is not %s", dir.c_str(), kFormat);
|
||||
const std::string form = m.value("format", std::string());
|
||||
if (form != kFormat && form != kFormatTop) {
|
||||
RAD_ERR("kld: %s/kld.json is neither %s nor %s", dir.c_str(), kFormat, kFormatTop);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if (m.value("n_vocab", (int64_t)0) != n_vocab_ || m.value("top", 0) != kKldTop) {
|
||||
sparse_ = form == kFormatTop;
|
||||
top_ = m.value("top", 0);
|
||||
rows_w_ = sparse_ ? 3 : 2;
|
||||
if (sparse_ ? (top_ < 1 || top_ > kKldTopMax || top_ > n_vocab_) : top_ != kKldTop) {
|
||||
RAD_ERR("kld: %s/kld.json keeps %d tokens a row, which a %s reference cannot", dir.c_str(),
|
||||
top_, form.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if (m.value("n_vocab", (int64_t)0) != n_vocab_) {
|
||||
RAD_ERR("kld: the reference in %s has a %lld-token vocabulary and this model %lld",
|
||||
dir.c_str(), (long long)m.value("n_vocab", (int64_t)0), (long long)n_vocab_);
|
||||
return RAD_E_INVAL;
|
||||
@@ -329,15 +431,17 @@ int Kld::load_ref(const std::string& dir) {
|
||||
const int fd = open_sized(dir + "/tokens.i32", n_tok * 4);
|
||||
const bool ok = fd >= 0 && pread_all(fd, tokens_.data(), (size_t)n_tok * 4, 0);
|
||||
if (fd >= 0) ::close(fd);
|
||||
fd_logp_ = open_sized(dir + "/logp.f16", n_rows_ * n_vocab_ * 2);
|
||||
fd_top_ = open_sized(dir + "/top.bin", n_rows_ * kKldTop * (int64_t)sizeof(TopEntry));
|
||||
fd_rows_ = open_sized(dir + "/rows.f32", n_rows_ * 2 * 4);
|
||||
if (!ok || fd_logp_ < 0 || fd_top_ < 0 || fd_rows_ < 0) {
|
||||
if (!sparse_) fd_logp_ = open_sized(dir + "/logp.f16", n_rows_ * n_vocab_ * 2);
|
||||
fd_top_ = open_sized(dir + "/top.bin", n_rows_ * top_ * (int64_t)sizeof(TopEntry));
|
||||
fd_rows_ = open_sized(dir + "/rows.f32", n_rows_ * rows_w_ * 4);
|
||||
if (!ok || (!sparse_ && fd_logp_ < 0) || fd_top_ < 0 || fd_rows_ < 0) {
|
||||
RAD_ERR("kld: the files in %s are missing or not the size kld.json says", dir.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_INFO("kld: scoring %lld positions over %zu documents against %s (%s)",
|
||||
(long long)n_rows_, docs_.size(), dir.c_str(), ref_model_.c_str());
|
||||
RAD_INFO("kld: scoring %lld positions over %zu documents against %s (%s, %s)",
|
||||
(long long)n_rows_, docs_.size(), dir.c_str(), ref_model_.c_str(),
|
||||
sparse_ ? fmt("its %d most likely tokens and the tail", top_).c_str()
|
||||
: "the whole vocabulary");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -357,11 +461,15 @@ int Kld::score(const std::vector<KldSpan>& spans, const std::vector<KldShard>& s
|
||||
|
||||
std::atomic<size_t> next{0};
|
||||
auto work = [&] {
|
||||
std::vector<uint16_t> f16((size_t)n_vocab_);
|
||||
Scratch w;
|
||||
if (sparse_) w.mark.assign((size_t)n_vocab_, 0);
|
||||
else w.f16.resize((size_t)n_vocab_);
|
||||
w.top.resize((size_t)top_);
|
||||
for (size_t i; (i = next.fetch_add(1, std::memory_order_relaxed)) < jobs.size();) {
|
||||
const Job& j = jobs[i];
|
||||
if (record_) record_row(j, shards, f16);
|
||||
else score_row(j, shards, f16);
|
||||
if (record_) record_row(j, shards, w);
|
||||
else if (sparse_) score_row_top(j, shards, w);
|
||||
else score_row(j, shards, w);
|
||||
if (!seen_[(size_t)j.row]) {
|
||||
seen_[(size_t)j.row] = 1;
|
||||
done_n_.fetch_add(1, std::memory_order_relaxed);
|
||||
@@ -380,52 +488,84 @@ int Kld::score(const std::vector<KldSpan>& spans, const std::vector<KldShard>& s
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The reference row: log-softmax over the whole vocabulary, summed in double. */
|
||||
void Kld::record_row(const Job& j, const std::vector<KldShard>& sh, std::vector<uint16_t>& f16) {
|
||||
float m = -std::numeric_limits<float>::infinity();
|
||||
for (const KldShard& s : sh) {
|
||||
const float* l = s.rows + j.at * s.width;
|
||||
for (int64_t i = 0; i < s.width; ++i) m = std::max(m, l[i]);
|
||||
}
|
||||
double sum = 0;
|
||||
for (const KldShard& s : sh) {
|
||||
const float* l = s.rows + j.at * s.width;
|
||||
for (int64_t i = 0; i < s.width; ++i) sum += std::exp(l[i] - m);
|
||||
}
|
||||
const double lse = (double)m + std::log(sum);
|
||||
|
||||
/* The head kept exactly: a min-heap on log p, so an entry leaves only for a strictly larger
|
||||
* one and a tie keeps the lower id, which is the candidate's argmax rule. */
|
||||
TopEntry top[kKldTop];
|
||||
/* The reference row: log-softmax over the whole vocabulary, summed in double.
|
||||
*
|
||||
* The sparse form picks its head by logit (one compare a token, the order log p has), then takes
|
||||
* every sum in one vectorised pass (row_sums). The head's smallest logit splits off the tail, so
|
||||
* the tail's mass is summed over the tokens outside the head rather than taken as one minus the
|
||||
* head, which would cancel to noise on a confident position. */
|
||||
void Kld::record_row(const Job& j, const std::vector<KldShard>& sh, Scratch& w) {
|
||||
TopEntry* top = w.top.data();
|
||||
int n_top = 0;
|
||||
auto worse = [](const TopEntry& a, const TopEntry& b) {
|
||||
return a.lp > b.lp || (a.lp == b.lp && a.id < b.id);
|
||||
};
|
||||
double ent = 0;
|
||||
for (const KldShard& s : sh) {
|
||||
const float* l = s.rows + j.at * s.width;
|
||||
for (int64_t i = 0; i < s.width; ++i) {
|
||||
const float lp = (float)((double)l[i] - lse);
|
||||
const int64_t id = s.vocab0 + i;
|
||||
f16[(size_t)id] = rad_f32_to_f16(lp);
|
||||
const double p = std::exp((double)lp);
|
||||
if (p > 0) ent -= p * (double)lp;
|
||||
if (n_top < kKldTop) {
|
||||
top[n_top++] = { (int32_t)id, lp };
|
||||
std::push_heap(top, top + n_top, worse);
|
||||
} else if (lp > top[0].lp) {
|
||||
std::pop_heap(top, top + n_top, worse);
|
||||
top[n_top - 1] = { (int32_t)id, lp };
|
||||
std::push_heap(top, top + n_top, worse);
|
||||
double lse = 0, ent = 0, tail = 0;
|
||||
if (sparse_) {
|
||||
/* The head kept exactly (worse() is its heap order), holding logits until lse is known. */
|
||||
for (const KldShard& s : sh) {
|
||||
const float* l = s.rows + j.at * s.width;
|
||||
for (int64_t i = 0; i < s.width; ++i) {
|
||||
if (n_top < top_) {
|
||||
top[n_top++] = { (int32_t)(s.vocab0 + i), l[i] };
|
||||
std::push_heap(top, top + n_top, worse);
|
||||
} else if (l[i] > top[0].lp) {
|
||||
std::pop_heap(top, top + n_top, worse);
|
||||
top[n_top - 1] = { (int32_t)(s.vocab0 + i), l[i] };
|
||||
std::push_heap(top, top + n_top, worse);
|
||||
}
|
||||
}
|
||||
}
|
||||
std::sort(top, top + n_top, worse);
|
||||
const float m = top[0].lp, thr = top[n_top - 1].lp;
|
||||
double S = 0, T = 0, rest = 0;
|
||||
int64_t eq = 0;
|
||||
for (const KldShard& s : sh) {
|
||||
const RowSums o = row_sums(s.rows + j.at * s.width, s.width, m, thr, nullptr);
|
||||
S += o.s; T += o.t; rest += o.rest; eq += o.eq;
|
||||
}
|
||||
/* The tokens at the threshold that the head left out (a tie keeps the lower ids). */
|
||||
for (int t = 0; t < n_top; ++t) eq -= top[t].lp == thr;
|
||||
rest += (double)eq * (double)exp_le0(thr - m);
|
||||
lse = (double)m + std::log(S);
|
||||
ent = std::log(S) - T / S;
|
||||
tail = rest / S;
|
||||
for (int t = 0; t < n_top; ++t) top[t].lp = (float)((double)top[t].lp - lse);
|
||||
} else {
|
||||
float m = -std::numeric_limits<float>::infinity();
|
||||
for (const KldShard& s : sh) {
|
||||
const float* l = s.rows + j.at * s.width;
|
||||
for (int64_t i = 0; i < s.width; ++i) m = std::max(m, l[i]);
|
||||
}
|
||||
double sum = 0;
|
||||
for (const KldShard& s : sh) {
|
||||
const float* l = s.rows + j.at * s.width;
|
||||
for (int64_t i = 0; i < s.width; ++i) sum += std::exp(l[i] - m);
|
||||
}
|
||||
lse = (double)m + std::log(sum);
|
||||
for (const KldShard& s : sh) {
|
||||
const float* l = s.rows + j.at * s.width;
|
||||
for (int64_t i = 0; i < s.width; ++i) {
|
||||
const float lp = (float)((double)l[i] - lse);
|
||||
const int64_t id = s.vocab0 + i;
|
||||
w.f16[(size_t)id] = rad_f32_to_f16(lp);
|
||||
const double p = std::exp((double)lp);
|
||||
if (p > 0) ent -= p * (double)lp;
|
||||
if (n_top < top_) {
|
||||
top[n_top++] = { (int32_t)id, lp };
|
||||
std::push_heap(top, top + n_top, worse);
|
||||
} else if (lp > top[0].lp) {
|
||||
std::pop_heap(top, top + n_top, worse);
|
||||
top[n_top - 1] = { (int32_t)id, lp };
|
||||
std::push_heap(top, top + n_top, worse);
|
||||
}
|
||||
}
|
||||
}
|
||||
std::sort(top, top + n_top, worse);
|
||||
}
|
||||
std::sort(top, top + n_top, worse);
|
||||
const float rows[2] = { (float)(lse - (double)logit_at(sh, j.at, j.next)), (float)ent };
|
||||
const float rows[3] = { (float)(lse - (double)logit_at(sh, j.at, j.next)), (float)ent, (float)tail };
|
||||
const int64_t r = j.row;
|
||||
if (!pwrite_all(fd_logp_, f16.data(), (size_t)n_vocab_ * 2, r * n_vocab_ * 2) ||
|
||||
!pwrite_all(fd_top_, top, sizeof top, r * (int64_t)sizeof top) ||
|
||||
!pwrite_all(fd_rows_, rows, sizeof rows, r * (int64_t)sizeof rows))
|
||||
const size_t top_b = (size_t)top_ * sizeof(TopEntry), rows_b = (size_t)rows_w_ * 4;
|
||||
if ((!sparse_ && !pwrite_all(fd_logp_, w.f16.data(), (size_t)n_vocab_ * 2, r * n_vocab_ * 2)) ||
|
||||
!pwrite_all(fd_top_, top, top_b, r * (int64_t)top_b) ||
|
||||
!pwrite_all(fd_rows_, rows, rows_b, r * (int64_t)rows_b))
|
||||
io_err_.store(1);
|
||||
}
|
||||
|
||||
@@ -437,7 +577,8 @@ void Kld::record_row(const Job& j, const std::vector<KldShard>& sh, std::vector<
|
||||
* the kKldTop most likely tokens). p is renormalised over the stored row (f16 rounding leaves
|
||||
* sum p a few 1e-5 off one): with S = sum e^{lp} and A = sum e^{lp} (lp - lq), KL = A / S -
|
||||
* log S. */
|
||||
void Kld::score_row(const Job& j, const std::vector<KldShard>& sh, std::vector<uint16_t>& f16) {
|
||||
void Kld::score_row(const Job& j, const std::vector<KldShard>& sh, Scratch& w) {
|
||||
std::vector<uint16_t>& f16 = w.f16;
|
||||
float m = -std::numeric_limits<float>::infinity();
|
||||
int64_t arg = 0;
|
||||
for (const KldShard& s : sh) {
|
||||
@@ -487,6 +628,75 @@ void Kld::score_row(const Job& j, const std::vector<KldShard>& sh, std::vector<u
|
||||
nll_p_[(size_t)r] = rows[0];
|
||||
}
|
||||
|
||||
/* The candidate row against a sparse reference: both distributions coarsened to the reference's
|
||||
* head H and one bucket T for every other token,
|
||||
*
|
||||
* KL(P' || Q') = sum_{i in H} p_i (log p_i - log q_i) + p_T (log p_T - log q_T)
|
||||
*
|
||||
* with p_T the reference's recorded tail mass and q_T this model's mass outside H, summed over its
|
||||
* own row (one minus its head would cancel to noise). p is renormalised over H and T as score_row
|
||||
* renormalises: with S = sum p and A the sum above, KL = A / S - log S. */
|
||||
void Kld::score_row_top(const Job& j, const std::vector<KldShard>& sh, Scratch& w) {
|
||||
float m = -std::numeric_limits<float>::infinity();
|
||||
int64_t arg = 0;
|
||||
for (const KldShard& s : sh) {
|
||||
const float* l = s.rows + j.at * s.width;
|
||||
for (int64_t i = 0; i < s.width; ++i)
|
||||
if (l[i] > m) { m = l[i]; arg = s.vocab0 + i; }
|
||||
}
|
||||
|
||||
TopEntry* top = w.top.data();
|
||||
float rows[3];
|
||||
const int64_t r = j.row;
|
||||
const size_t top_b = (size_t)top_ * sizeof(TopEntry);
|
||||
if (!pread_all(fd_top_, top, top_b, r * (int64_t)top_b) ||
|
||||
!pread_all(fd_rows_, rows, sizeof rows, r * (int64_t)sizeof rows)) {
|
||||
io_err_.store(1);
|
||||
return;
|
||||
}
|
||||
|
||||
/* The row's sum and its part outside the head in one vectorised pass (row_sums). */
|
||||
for (int t = 0; t < top_; ++t) w.mark[(size_t)top[t].id] = 1;
|
||||
double sum = 0, rest = 0;
|
||||
for (const KldShard& s : sh) {
|
||||
const RowSums o = row_sums(s.rows + j.at * s.width, s.width, m, 0.0f, w.mark.data() + s.vocab0);
|
||||
sum += o.s; rest += o.rest;
|
||||
}
|
||||
const double lse = (double)m + std::log(sum);
|
||||
double q_tail = rest / sum;
|
||||
/* row_sums flushes a token below e^-87 of the max to zero. A candidate whose whole tail is
|
||||
* that small is summed again in double, so q_T stays its true size rather than none. */
|
||||
if (q_tail < 1e-30) {
|
||||
q_tail = 0;
|
||||
for (const KldShard& s : sh) {
|
||||
const float* l = s.rows + j.at * s.width;
|
||||
for (int64_t i = 0; i < s.width; ++i)
|
||||
if (!w.mark[(size_t)(s.vocab0 + i)]) q_tail += std::exp((double)l[i] - lse);
|
||||
}
|
||||
}
|
||||
for (int t = 0; t < top_; ++t) w.mark[(size_t)top[t].id] = 0;
|
||||
|
||||
double S = 0, A = 0;
|
||||
for (int t = 0; t < top_; ++t) {
|
||||
const double lp = (double)top[t].lp, lq = (double)logit_at(sh, j.at, top[t].id) - lse;
|
||||
const double p = std::exp(lp);
|
||||
if (!(p > 0)) continue;
|
||||
S += p;
|
||||
A += p * (lp - lq);
|
||||
}
|
||||
const double p_tail = (double)rows[2];
|
||||
if (p_tail > 0) {
|
||||
S += p_tail;
|
||||
/* A head that holds every token the candidate gives mass to leaves q_T zero: the smallest
|
||||
* normal double stands in, so the bucket costs what an impossible event costs, finitely. */
|
||||
A += p_tail * (std::log(p_tail) - std::log(std::max(q_tail, std::numeric_limits<double>::min())));
|
||||
}
|
||||
kl_[(size_t)r] = (float)(A / S - std::log(S));
|
||||
top1_[(size_t)r] = arg == (int64_t)top[0].id;
|
||||
nll_q_[(size_t)r] = (float)(lse - (double)logit_at(sh, j.at, j.next));
|
||||
nll_p_[(size_t)r] = rows[0];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the end */
|
||||
int Kld::finish() {
|
||||
const int64_t missing = n_rows_ - done_n_.load();
|
||||
@@ -498,15 +708,15 @@ int Kld::finish() {
|
||||
if (!record_) return report();
|
||||
|
||||
for (int fd : { fd_logp_, fd_top_, fd_rows_ })
|
||||
if (::fsync(fd) != 0) { RAD_ERR("kld: fsync: %s", std::strerror(errno)); return RAD_E_IO; }
|
||||
if (fd >= 0 && ::fsync(fd) != 0) { RAD_ERR("kld: fsync: %s", std::strerror(errno)); return RAD_E_IO; }
|
||||
json m;
|
||||
m["format"] = kFormat;
|
||||
m["format"] = sparse_ ? kFormatTop : kFormat;
|
||||
m["model"] = model_;
|
||||
m["corpus"] = corpus_;
|
||||
m["corpus_fnv1a64"] = fmt("%016llx", (unsigned long long)corpus_hash_);
|
||||
m["created"] = now_iso();
|
||||
m["n_vocab"] = n_vocab_;
|
||||
m["top"] = kKldTop;
|
||||
m["top"] = top_;
|
||||
m["rows"] = n_rows_;
|
||||
json docs = json::array();
|
||||
for (const Doc& d : docs_)
|
||||
@@ -558,6 +768,7 @@ int Kld::report() {
|
||||
rep["model"] = model_;
|
||||
rep["reference"] = ref_model_;
|
||||
rep["ref_dir"] = dir_;
|
||||
rep["ref_form"] = sparse_ ? fmt("top-%d + tail", top_) : std::string("full vocabulary");
|
||||
rep["corpus"] = corpus_;
|
||||
rep["created"] = now_iso();
|
||||
rep["docs"] = (int64_t)docs_.size();
|
||||
|
||||
Reference in new issue
Block a user