Datasets:
Download tools/llama_kld.cpp from StillDeadcode/qwen3.8-27b-quant-challenge: direct link, hf CLI and curl.
- Browser
- Download file 16.6 kB
-
https://huggingface.co/datasets/StillDeadcode/qwen3.8-27b-quant-challenge/resolve/main/tools/llama_kld.cpp
- Command line
-
hf download hf://datasets/StillDeadcode/qwen3.8-27b-quant-challenge/tools/llama_kld.cpp
-
curl -L -o llama_kld.cpp https://huggingface.co/datasets/StillDeadcode/qwen3.8-27b-quant-challenge/resolve/main/tools/llama_kld.cpp
16.6 kB
| // llama_kld.cpp -- scores a GGUF model run by llama.cpp against a sparse radiance KL reference | |
| // (radiance --kld-record DIR --kld-top N, format radiance-kld-top-1), with the same arithmetic as | |
| // radiance's --kld-ref (core/kld.cpp, Kld::score_row_top), so a llama.cpp quant and a radiance one | |
| // are measured against one reference in one way. | |
| // | |
| // The reference's own tokens are fed (tokens.i32), never a re-tokenisation, one document at a time | |
| // from an empty cache. Every scored position's logits come back from llama.cpp in f32; the | |
| // candidate's distribution is its softmax over its whole row, and the KL is that of both | |
| // distributions coarsened to the reference's N tokens and one bucket for every other token: | |
| // | |
| // KL = sum_{i in head} p_i (log p_i - log q_i) + p_tail (log p_tail - log q_tail) | |
| // | |
| // with p renormalised over head and tail (S = sum p; KL = A / S - log S), q_tail summed over the | |
| // candidate's own row outside the head. | |
| // | |
| // llama_kld --model M.gguf --ref DIR --out REPORT.json [--ctx N] [--batch N] [--ubatch N] | |
| // [--kv bf16|f16] [--split layer|row|none] [--threads N] | |
| namespace { | |
| struct TopEntry { int32_t id; float lp; }; | |
| struct Doc { | |
| std::string source; | |
| int64_t off = 0, n = 0, score_from = 0, row0 = 0; | |
| int64_t rows() const { return n - 1 - score_from; } | |
| }; | |
| // A minimal reader for the fields of kld.json this tool needs. The manifest is written by | |
| // radiance's nlohmann::json dump; values are numbers or strings without escapes beyond \". | |
| struct Manifest { | |
| std::string format, model; | |
| int64_t n_vocab = 0, rows = 0; | |
| int top = 0; | |
| std::vector<Doc> docs; | |
| }; | |
| std::string read_all(const std::string& p) { | |
| std::ifstream in(p, std::ios::binary); | |
| std::stringstream ss; | |
| ss << in.rdbuf(); | |
| return ss.str(); | |
| } | |
| std::string str_after(const std::string& s, size_t& at, const char* key) { | |
| const std::string k = std::string("\"") + key + "\""; | |
| size_t p = s.find(k, at); | |
| if (p == std::string::npos) return {}; | |
| p = s.find(':', p + k.size()); | |
| p = s.find('"', p); | |
| std::string out; | |
| for (size_t i = p + 1; i < s.size(); ++i) { | |
| if (s[i] == '\\' && i + 1 < s.size()) { out += s[++i]; continue; } | |
| if (s[i] == '"') { at = i + 1; return out; } | |
| out += s[i]; | |
| } | |
| return out; | |
| } | |
| int64_t num_after(const std::string& s, size_t& at, const char* key) { | |
| const std::string k = std::string("\"") + key + "\""; | |
| size_t p = s.find(k, at); | |
| if (p == std::string::npos) return -1; | |
| p = s.find(':', p + k.size()) + 1; | |
| while (p < s.size() && (s[p] == ' ' || s[p] == '\n')) ++p; | |
| char* end = nullptr; | |
| const long long v = std::strtoll(s.c_str() + p, &end, 10); | |
| at = (size_t)(end - s.c_str()); | |
| return v; | |
| } | |
| bool load_manifest(const std::string& dir, Manifest& m) { | |
| const std::string s = read_all(dir + "/kld.json"); | |
| if (s.empty()) return false; | |
| size_t at = 0; | |
| m.format = str_after(s, at, "format"); | |
| at = 0; m.model = str_after(s, at, "model"); | |
| at = 0; m.n_vocab = num_after(s, at, "n_vocab"); | |
| at = 0; m.top = (int)num_after(s, at, "top"); | |
| at = 0; m.rows = num_after(s, at, "rows"); | |
| size_t p = s.find("\"docs\""); | |
| if (p == std::string::npos) return false; | |
| int64_t off = 0; | |
| while (true) { | |
| const size_t q = s.find('{', p); | |
| if (q == std::string::npos) break; | |
| size_t at2 = q; | |
| Doc d; | |
| d.source = str_after(s, at2, "source"); | |
| d.n = num_after(s, at2, "tokens"); | |
| d.score_from = num_after(s, at2, "score_from"); | |
| d.row0 = num_after(s, at2, "row0"); | |
| d.off = off; | |
| off += d.n; | |
| m.docs.push_back(d); | |
| p = s.find('}', at2); | |
| if (p == std::string::npos) break; | |
| } | |
| return m.format == "radiance-kld-top-1" && m.top > 0 && m.n_vocab > 0 && !m.docs.empty(); | |
| } | |
| bool pread_all(int fd, void* p, size_t n, int64_t off) { | |
| auto* b = static_cast<char*>(p); | |
| while (n) { | |
| const ssize_t r = ::pread(fd, b, n, (off_t)off); | |
| if (r <= 0) return false; | |
| b += r; n -= (size_t)r; off += r; | |
| } | |
| return true; | |
| } | |
| double quantile(const std::vector<float>& v, double q) { | |
| if (v.empty()) return 0; | |
| const double x = q * (double)(v.size() - 1); | |
| const size_t i = (size_t)x; | |
| if (i + 1 >= v.size()) return v.back(); | |
| return v[i] + (x - (double)i) * (v[i + 1] - v[i]); | |
| } | |
| std::string summary(std::vector<float> kl, int64_t t1, double nq, double np) { | |
| char buf[1024]; | |
| const size_t n = kl.size(); | |
| if (!n) return "{}"; | |
| std::sort(kl.begin(), kl.end()); | |
| double sum = 0; | |
| for (float v : kl) sum += v; | |
| std::snprintf(buf, sizeof buf, | |
| "{\"positions\": %zu, \"kld\": {\"mean\": %.9g, \"median\": %.9g, \"p90\": %.9g, " | |
| "\"p95\": %.9g, \"p99\": %.9g, \"p99_9\": %.9g, \"p99_99\": %.9g, \"max\": %.9g}, " | |
| "\"top1_agreement\": %.9g, \"ppl\": {\"candidate\": %.9g, \"reference\": %.9g, " | |
| "\"ratio\": %.9g}}", | |
| n, sum / n, quantile(kl, 0.5), quantile(kl, 0.9), quantile(kl, 0.95), | |
| quantile(kl, 0.99), quantile(kl, 0.999), quantile(kl, 0.9999), (double)kl.back(), | |
| (double)t1 / n, std::exp(nq / n), std::exp(np / n), std::exp((nq - np) / n)); | |
| return buf; | |
| } | |
| std::string jesc(const std::string& s) { | |
| std::string o; | |
| for (char c : s) { if (c == '"' || c == '\\') o += '\\'; o += c; } | |
| return o; | |
| } | |
| } // namespace | |
| int main(int argc, char** argv) { | |
| std::string model, ref, out, kv = "bf16", split = "layer"; | |
| int64_t n_ctx = 0; | |
| int n_batch = 2048, n_ubatch = 512, n_threads = (int)std::max(1u, std::thread::hardware_concurrency() - 2); | |
| for (int i = 1; i < argc; ++i) { | |
| const std::string a = argv[i]; | |
| auto next = [&]() -> const char* { if (i + 1 >= argc) { fprintf(stderr, "%s needs a value\n", a.c_str()); exit(2); } return argv[++i]; }; | |
| if (a == "--model") model = next(); | |
| else if (a == "--ref") ref = next(); | |
| else if (a == "--out") out = next(); | |
| else if (a == "--ctx") n_ctx = std::atoll(next()); | |
| else if (a == "--batch") n_batch = std::atoi(next()); | |
| else if (a == "--ubatch") n_ubatch = std::atoi(next()); | |
| else if (a == "--kv") kv = next(); | |
| else if (a == "--split") split = next(); | |
| else if (a == "--threads") n_threads = std::atoi(next()); | |
| else { fprintf(stderr, "unknown argument %s\n", a.c_str()); return 2; } | |
| } | |
| if (model.empty() || ref.empty() || out.empty()) { | |
| fprintf(stderr, "usage: llama_kld --model M.gguf --ref DIR --out REPORT.json [--ctx N] " | |
| "[--batch N] [--ubatch N] [--kv bf16|f16] [--split layer|row|none] [--threads N]\n"); | |
| return 2; | |
| } | |
| Manifest man; | |
| if (!load_manifest(ref, man)) { | |
| fprintf(stderr, "llama_kld: %s/kld.json is not a radiance-kld-top-1 reference\n", ref.c_str()); | |
| return 1; | |
| } | |
| int64_t n_tok = 0, longest = 0, rows = 0; | |
| for (const Doc& d : man.docs) { n_tok += d.n; longest = std::max(longest, d.n); rows += d.rows(); } | |
| if (rows != man.rows) { fprintf(stderr, "llama_kld: documents add up to %lld rows, manifest %lld\n", (long long)rows, (long long)man.rows); return 1; } | |
| std::vector<int32_t> tokens((size_t)n_tok); | |
| const int fd_tok = ::open((ref + "/tokens.i32").c_str(), O_RDONLY); | |
| const int fd_top = ::open((ref + "/top.bin").c_str(), O_RDONLY); | |
| const int fd_rows = ::open((ref + "/rows.f32").c_str(), O_RDONLY); | |
| if (fd_tok < 0 || fd_top < 0 || fd_rows < 0 || !pread_all(fd_tok, tokens.data(), (size_t)n_tok * 4, 0)) { | |
| fprintf(stderr, "llama_kld: cannot read the reference files in %s\n", ref.c_str()); | |
| return 1; | |
| } | |
| const int top = man.top; | |
| if (n_ctx <= 0) n_ctx = longest + 16; | |
| llama_backend_init(); | |
| llama_model_params mp = llama_model_default_params(); | |
| mp.n_gpu_layers = 999; | |
| mp.split_mode = split == "row" ? LLAMA_SPLIT_MODE_ROW : split == "none" ? LLAMA_SPLIT_MODE_NONE : LLAMA_SPLIT_MODE_LAYER; | |
| llama_model* lm = llama_model_load_from_file(model.c_str(), mp); | |
| if (!lm) { fprintf(stderr, "llama_kld: cannot load %s\n", model.c_str()); return 1; } | |
| const llama_vocab* vocab = llama_model_get_vocab(lm); | |
| const int64_t nv = llama_vocab_n_tokens(vocab); | |
| llama_context_params cp = llama_context_default_params(); | |
| cp.n_ctx = (uint32_t)n_ctx; | |
| cp.n_batch = (uint32_t)n_batch; | |
| cp.n_ubatch = (uint32_t)n_ubatch; | |
| cp.n_seq_max = 1; | |
| cp.type_k = cp.type_v = kv == "f16" ? GGML_TYPE_F16 : GGML_TYPE_BF16; | |
| cp.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED; | |
| cp.n_threads = cp.n_threads_batch = n_threads; | |
| cp.no_perf = true; | |
| llama_context* ctx = llama_init_from_model(lm, cp); | |
| if (!ctx) { fprintf(stderr, "llama_kld: cannot create a %lld-token context\n", (long long)n_ctx); return 1; } | |
| fprintf(stderr, "llama_kld: %s, vocab %lld (reference %lld), %zu documents, %lld positions, top-%d, " | |
| "ctx %lld, kv %s\n", model.c_str(), (long long)nv, (long long)man.n_vocab, | |
| man.docs.size(), (long long)rows, top, (long long)n_ctx, kv.c_str()); | |
| for (const Doc& d : man.docs) | |
| for (int64_t i = 0; i < d.n; ++i) | |
| if (tokens[(size_t)(d.off + i)] >= nv) { | |
| fprintf(stderr, "llama_kld: token %d is outside the model's %lld-token vocabulary\n", | |
| tokens[(size_t)(d.off + i)], (long long)nv); | |
| return 1; | |
| } | |
| std::vector<float> kl((size_t)rows), nq((size_t)rows), np((size_t)rows); | |
| std::vector<uint8_t> t1((size_t)rows); | |
| std::atomic<int> io_err{0}; | |
| llama_batch batch = llama_batch_init(n_batch, 0, 1); | |
| const time_t t0 = time(nullptr); | |
| int64_t done = 0; | |
| for (size_t di = 0; di < man.docs.size(); ++di) { | |
| const Doc& d = man.docs[di]; | |
| llama_memory_clear(llama_get_memory(ctx), true); | |
| for (int64_t p0 = 0; p0 < d.n; p0 += n_batch) { | |
| const int64_t m = std::min<int64_t>(n_batch, d.n - p0); | |
| batch.n_tokens = (int32_t)m; | |
| std::vector<int64_t> scored; // batch index -> document position | |
| for (int64_t j = 0; j < m; ++j) { | |
| const int64_t p = p0 + j; | |
| batch.token[j] = tokens[(size_t)(d.off + p)]; | |
| batch.pos[j] = (llama_pos)p; | |
| batch.n_seq_id[j] = 1; | |
| batch.seq_id[j][0] = 0; | |
| const bool s = p >= d.score_from && p < d.n - 1; | |
| batch.logits[j] = s; | |
| if (s) scored.push_back(j); | |
| } | |
| if (llama_decode(ctx, batch) != 0) { | |
| fprintf(stderr, "llama_kld: llama_decode failed in document %zu at %lld\n", di, (long long)p0); | |
| return 1; | |
| } | |
| // The scored rows of this batch, split over threads. | |
| std::atomic<size_t> next{0}; | |
| auto work = [&] { | |
| std::vector<TopEntry> head((size_t)top); | |
| std::vector<uint8_t> mark((size_t)nv, 0); | |
| float rr[3]; | |
| for (size_t k; (k = next.fetch_add(1)) < scored.size();) { | |
| const int64_t j = scored[k], p = p0 + j, r = d.row0 + p - d.score_from; | |
| const float* l = llama_get_logits_ith(ctx, (int32_t)j); | |
| if (!l || !pread_all(fd_top, head.data(), (size_t)top * sizeof(TopEntry), r * (int64_t)top * (int64_t)sizeof(TopEntry)) || | |
| !pread_all(fd_rows, rr, sizeof rr, r * (int64_t)sizeof rr)) { io_err = 1; continue; } | |
| float mx = -std::numeric_limits<float>::infinity(); | |
| int64_t arg = 0; | |
| for (int64_t i = 0; i < nv; ++i) if (l[i] > mx) { mx = l[i]; arg = i; } | |
| double sum = 0; | |
| for (int64_t i = 0; i < nv; ++i) sum += std::exp((double)(l[i] - mx)); | |
| const double lse = (double)mx + std::log(sum); | |
| double S = 0, A = 0; | |
| for (int t = 0; t < top; ++t) { | |
| const int32_t id = head[(size_t)t].id; | |
| const double lp = head[(size_t)t].lp; | |
| const double lq = id < nv ? (double)l[id] - lse : -std::numeric_limits<double>::infinity(); | |
| if (id < nv) mark[(size_t)id] = 1; | |
| const double pp = std::exp(lp); | |
| if (!(pp > 0)) continue; | |
| S += pp; | |
| A += pp * (lp - lq); | |
| } | |
| double q_tail = 0; | |
| for (int64_t i = 0; i < nv; ++i) if (!mark[(size_t)i]) q_tail += std::exp((double)l[i] - lse); | |
| for (int t = 0; t < top; ++t) if (head[(size_t)t].id < nv) mark[(size_t)head[(size_t)t].id] = 0; | |
| const double p_tail = rr[2]; | |
| if (p_tail > 0) { | |
| S += p_tail; | |
| A += p_tail * (std::log(p_tail) - std::log(std::max(q_tail, std::numeric_limits<double>::min()))); | |
| } | |
| const int32_t nxt = tokens[(size_t)(d.off + p + 1)]; | |
| kl[(size_t)r] = (float)(A / S - std::log(S)); | |
| t1[(size_t)r] = arg == (int64_t)head[0].id; | |
| nq[(size_t)r] = (float)(lse - (double)l[nxt]); | |
| np[(size_t)r] = rr[0]; | |
| } | |
| }; | |
| const int nt = (int)std::min<size_t>((size_t)n_threads, std::max<size_t>(1, scored.size())); | |
| std::vector<std::thread> th; | |
| for (int t = 0; t < nt; ++t) th.emplace_back(work); | |
| for (auto& t : th) t.join(); | |
| if (io_err) { fprintf(stderr, "llama_kld: reading the reference failed\n"); return 1; } | |
| done += (int64_t)scored.size(); | |
| } | |
| if (di % 50 == 0 || di + 1 == man.docs.size()) | |
| fprintf(stderr, "llama_kld: %zu / %zu documents, %lld / %lld positions, %lld s\n", di + 1, | |
| man.docs.size(), (long long)done, (long long)rows, (long long)(time(nullptr) - t0)); | |
| } | |
| // The report, in radiance's --kld-out layout. | |
| auto group = [&](const std::vector<size_t>& ds) { | |
| std::vector<float> v; | |
| int64_t a = 0; | |
| double q = 0, p = 0; | |
| for (size_t di : ds) { | |
| const Doc& d = man.docs[di]; | |
| for (int64_t r = d.row0; r < d.row0 + d.rows(); ++r) { | |
| v.push_back(kl[(size_t)r]); a += t1[(size_t)r]; q += nq[(size_t)r]; p += np[(size_t)r]; | |
| } | |
| } | |
| return summary(std::move(v), a, q, p); | |
| }; | |
| std::vector<size_t> all(man.docs.size()); | |
| std::map<std::string, std::vector<size_t>> by; | |
| for (size_t i = 0; i < man.docs.size(); ++i) { all[i] = i; by[man.docs[i].source].push_back(i); } | |
| std::ofstream o(out); | |
| char tb[32]; | |
| const time_t now = time(nullptr); | |
| std::strftime(tb, sizeof tb, "%Y-%m-%dT%H:%M:%SZ", gmtime(&now)); | |
| o << "{\n \"model\": \"" << jesc(model) << "\",\n \"engine\": \"llama.cpp\",\n \"reference\": \"" | |
| << jesc(man.model) << "\",\n \"ref_dir\": \"" << jesc(ref) << "\",\n \"ref_form\": \"top-" << top | |
| << " + tail\",\n \"kv\": \"" << kv << "\",\n \"created\": \"" << tb << "\",\n \"docs\": " | |
| << man.docs.size() << ",\n \"all\": " << group(all) << ",\n \"by_source\": {"; | |
| bool first = true; | |
| for (const auto& [name, ds] : by) { | |
| o << (first ? "\n" : ",\n") << " \"" << jesc(name) << "\": " << group(ds); | |
| first = false; | |
| } | |
| o << "\n }\n}\n"; | |
| o.close(); | |
| std::vector<float> rr((size_t)rows * 4); | |
| for (int64_t r = 0; r < rows; ++r) { | |
| rr[(size_t)r * 4] = kl[(size_t)r]; rr[(size_t)r * 4 + 1] = nq[(size_t)r]; | |
| rr[(size_t)r * 4 + 2] = np[(size_t)r]; rr[(size_t)r * 4 + 3] = t1[(size_t)r]; | |
| } | |
| std::ofstream orow(out + ".rows", std::ios::binary); | |
| orow.write(reinterpret_cast<const char*>(rr.data()), (std::streamsize)(rr.size() * sizeof(float))); | |
| fprintf(stderr, "llama_kld: report in %s: %s\n", out.c_str(), group(all).c_str()); | |
| llama_batch_free(batch); | |
| llama_free(ctx); | |
| llama_model_free(lm); | |
| return 0; | |
| } | |