tools: the real-file reference and the per-position logits comparison

ref/qwen36.py --all-logits dumps result_output_all (the head at every position
of the last chunk), the reference a streaming runner is held to position by
position.  qwen36_prefill_fixture.py's write() gains q8_embd (token_embd.weight
as Q8_0, a type a native pack's embedding kernel serves), reused by the runner
fixture.

qwen36_teacher_llama.cpp is llama.cpp's own greedy continuation of a prompt with
the head's logits per position and the routed experts at probed layers;
qwen36_compare_logits.py scores top-1 agreement, KL(ref || engine) per position,
the drift gate (one-sided: only a KL that rises with position is a leaking
state) and the routed-selection overlap.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017tPVMg2wGSNR1KANEiUtwr
This commit is contained in:
Robert KarlandClaude Fable 5.1 committed 2026-10-12 18:30:29 -07:00
1 parent bc0b297069
commit bcc7cc8960
4 files changed
+343 -5

No files matched your search

+4 -2
View File
@@ -647,6 +647,8 @@ def main() -> int:
ap.add_argument("--force-topk", metavar="DIR", help="use the expert choices in DIR/ffn_moe_topk-<layer>.f32 (e.g. a llama.cpp dump) instead of the router's own")
ap.add_argument("--force-inputs", metavar="DIR", help="start every layer from DIR/l_out-<il-1>.f32 (a llama.cpp dump of the same tokens): measures per-layer, not accumulated, error")
ap.add_argument("--mtp", action="store_true", help="also run the nextn block on (tokens[1:], trunk hidden[:-1])")
ap.add_argument("--all-logits", action="store_true",
help="also dump result_output_all: the head's logits at every position of the (last) chunk, for a runner held to the oracle position by position")
a = ap.parse_args()
toks = [int(t) for t in a.tokens.split(",")] if a.tokens else [ord(c) for c in a.text]
m = Model(a.gguf)
@@ -664,9 +666,9 @@ def main() -> int:
st = None
for i in range(0, len(toks), a.split):
last = i + a.split >= len(toks)
logits, h, st = m.forward(toks[i:i + a.split], d if last else None, st)
logits, h, st = m.forward(toks[i:i + a.split], d if last else None, st, all_logits=a.all_logits)
else:
logits, h, _ = m.forward(toks, d)
logits, h, _ = m.forward(toks, d, all_logits=a.all_logits)
print(f"{len(toks)} tokens; last-token logits: argmax {int(logits.argmax())}, max {logits.max():.6f}, sum {logits.sum():.6f}")
d.close()
if a.mtp:
+5 -3
View File
@@ -83,8 +83,10 @@ def cfg(case: str, seed: int) -> qs.Cfg:
return c
def write(path: str, c: qs.Cfg) -> tuple[int, int]:
"""qwen36_synth_gguf.write with the per-tensor forms above. Returns (tensors, q8 tensors)."""
def write(path: str, c: qs.Cfg, q8_embd: bool = False) -> tuple[int, int]:
"""qwen36_synth_gguf.write with the per-tensor forms above. Returns (tensors, q8 tensors). `q8_embd` writes
token_embd.weight as Q8_0 too (a native pack's embedding must be a type iq_embed_rows serves: the runner's fixture,
tests/python/qwen36_runner_fixture.py); the prompt-path harness keeps it F32."""
w = GGUFWriter(path, qs.ARCH)
k = lambda s: f"{qs.ARCH}.{s}"
w.add_name("qwen36-synth prefill-geometry")
@@ -122,7 +124,7 @@ def write(path: str, c: qs.Cfg) -> tuple[int, int]:
n, nq = 0, 0
for name, arr in qs.build_tensors(c):
n += 1
if name.endswith(Q8_SUFFIXES) or name == "output.weight":
if name.endswith(Q8_SUFFIXES) or name == "output.weight" or (q8_embd and name == "token_embd.weight"):
w.add_tensor(name, quants.quantize(arr, Q.Q8_0), raw_dtype=Q.Q8_0) # the byte shape; gguf-py derives the elements
nq += 1
elif name.endswith(BF16_SUFFIXES):
+155
View File
@@ -0,0 +1,155 @@
#!/usr/bin/env python3
"""tools/qwen36_compare_logits.py - the engine's per-position logits against a reference's, teacher-forced.
python3 -I tools/qwen36_compare_logits.py ENGINE.f32 REFERENCE.f32 --n-vocab N [--engine-header] [--rows R]
[--routes-engine F --routes-ref F] [--json OUT]
ENGINE.f32 is `strata --dump-logits` (two int32, n_vocab and rows, then the rows; --engine-header is the default)
or raw rows; REFERENCE.f32 is raw rows of n_vocab F32 (tools/qwen36_teacher_llama.cpp's logits.f32, or the oracle's
result_output_all). Row j of both is the distribution at the same position. Reports, per position and summarised:
top-1 agreement the argmax of the two rows equal
KL(ref || engine) in nats, from the softmax of each row (mean, max, the position of the max)
drift Maya's quantized-mode gate: KL must not rise monotonically with the position - the slope of
KL against the position (least squares) and the Spearman rank correlation are printed; the
gate (--max-spearman) is one-sided - only a RISING KL is drift (Spearman > the bound), a
chaotic spread is flat and a falling KL is not drift
routes with --routes-*: "<row> <layer> e0 .. e7" lines from both sides, the share of probed
(row, layer) pairs whose top-k SETS are equal
Exit 1 when a gate given on the command line fails (--min-top1, --max-mean-kl, --max-max-kl, --max-spearman).
"""
import argparse
import json
import sys
import numpy as np
def load_engine(path, n_vocab, header):
a = np.fromfile(path, dtype=np.float32)
if header:
h = np.frombuffer(a[:2].tobytes(), dtype=np.int32)
if int(h[0]) != n_vocab:
raise SystemExit(f"{path}: header says n_vocab {int(h[0])}, expected {n_vocab}")
a = a[2:]
rows = int(h[1])
if a.size != rows * n_vocab:
raise SystemExit(f"{path}: header promises {rows} rows, the file holds {a.size / n_vocab:.2f}")
return a.reshape(-1, n_vocab)
def softmax(x):
x = x.astype(np.float64)
x = x - x.max(axis=1, keepdims=True)
e = np.exp(x)
return e / e.sum(axis=1, keepdims=True)
def spearman(x, y):
rx = np.argsort(np.argsort(x)).astype(np.float64)
ry = np.argsort(np.argsort(y)).astype(np.float64)
if rx.std() == 0 or ry.std() == 0:
return 0.0
return float(np.corrcoef(rx, ry)[0, 1])
def read_routes(path):
out = {}
for line in open(path):
parts = line.split()
if len(parts) < 3:
continue
row, layer = int(parts[0]), int(parts[1])
out[(row, layer)] = frozenset(int(p) for p in parts[2:])
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("engine")
ap.add_argument("reference")
ap.add_argument("--n-vocab", type=int, required=True)
ap.add_argument("--engine-header", action="store_true", default=True)
ap.add_argument("--no-engine-header", dest="engine_header", action="store_false")
ap.add_argument("--rows", type=int, default=0, help="compare this many rows (0 = all common rows)")
ap.add_argument("--routes-engine")
ap.add_argument("--routes-ref")
ap.add_argument("--json")
ap.add_argument("--min-top1", type=float)
ap.add_argument("--max-mean-kl", type=float)
ap.add_argument("--max-max-kl", type=float)
ap.add_argument("--max-spearman", type=float)
ap.add_argument("--quiet", action="store_true")
a = ap.parse_args()
e = load_engine(a.engine, a.n_vocab, a.engine_header)
r = np.fromfile(a.reference, dtype=np.float32).reshape(-1, a.n_vocab)
n = min(e.shape[0], r.shape[0])
if a.rows:
n = min(n, a.rows)
if n == 0:
raise SystemExit("no rows to compare")
e, r = e[:n], r[:n]
pe, pr = softmax(e), softmax(r)
kl = np.sum(pr * (np.log(pr + 1e-30) - np.log(pe + 1e-30)), axis=1)
top1 = (e.argmax(axis=1) == r.argmax(axis=1))
top5 = np.array([len(set(np.argsort(-e[i])[:5]) & set(np.argsort(-r[i])[:5])) for i in range(n)])
pos = np.arange(n, dtype=np.float64)
slope = float(np.polyfit(pos, kl, 1)[0]) if n > 1 else 0.0
rho = spearman(pos, kl) if n > 1 else 0.0
res = {"rows": int(n), "top1": int(top1.sum()), "top1_rate": float(top1.mean()), "kl_mean": float(kl.mean()),
"kl_max": float(kl.max()), "kl_argmax": int(kl.argmax()), "kl_median": float(np.median(kl)),
"kl_first_half": float(kl[: n // 2].mean()), "kl_second_half": float(kl[n // 2:].mean()),
"kl_slope_per_position": slope, "kl_spearman": rho, "top5_overlap_mean": float(top5.mean()),
"rows_top1_differ": [int(i) for i in np.nonzero(~top1)[0]]}
if a.routes_engine and a.routes_ref:
re_, rr = read_routes(a.routes_engine), read_routes(a.routes_ref)
common = sorted(set(re_) & set(rr))
equal = sum(1 for k in common if re_[k] == rr[k])
by_layer = {}
for k in common:
by_layer.setdefault(k[1], [0, 0])
by_layer[k[1]][1] += 1
by_layer[k[1]][0] += re_[k] == rr[k]
res["routes_pairs"] = len(common)
res["routes_equal"] = equal
res["routes_by_layer"] = {str(l): f"{v[0]}/{v[1]}" for l, v in sorted(by_layer.items())}
slot_eq = []
for k in common:
slot_eq.append(len(re_[k] & rr[k]) / max(1, len(rr[k])))
res["routes_slot_overlap_mean"] = float(np.mean(slot_eq)) if slot_eq else 0.0
if not a.quiet:
print(f"{n} positions: top-1 agreement {res['top1']}/{n} ({res['top1_rate']:.4f}), top-5 overlap "
f"{res['top5_overlap_mean']:.2f}/5")
print(f"KL(ref||engine): mean {res['kl_mean']:.5f} median {res['kl_median']:.5f} max {res['kl_max']:.5f} "
f"at position {res['kl_argmax']}; first half {res['kl_first_half']:.5f}, second half {res['kl_second_half']:.5f}")
print(f"drift: KL slope {slope:+.2e} per position, Spearman(position, KL) {rho:+.3f}")
if res["rows_top1_differ"]:
print("top-1 differs at positions: " + ", ".join(map(str, res["rows_top1_differ"][:40])) +
(" ..." if len(res["rows_top1_differ"]) > 40 else ""))
if "routes_pairs" in res:
print(f"routes: {res['routes_equal']}/{res['routes_pairs']} probed (row, layer) top-k sets equal "
f"(per layer {res['routes_by_layer']}); mean slot overlap {res['routes_slot_overlap_mean']:.3f}")
print("per position (pos top1 kl):")
print(" ".join(f"{i}:{'=' if top1[i] else 'x'}{kl[i]:.3f}" for i in range(n)))
if a.json:
with open(a.json, "w") as f:
json.dump(res, f, indent=1)
bad = []
if a.min_top1 is not None and res["top1_rate"] < a.min_top1:
bad.append(f"top-1 {res['top1_rate']:.4f} < {a.min_top1}")
if a.max_mean_kl is not None and res["kl_mean"] > a.max_mean_kl:
bad.append(f"mean KL {res['kl_mean']:.5f} > {a.max_mean_kl}")
if a.max_max_kl is not None and res["kl_max"] > a.max_max_kl:
bad.append(f"max KL {res['kl_max']:.5f} > {a.max_max_kl}")
if a.max_spearman is not None and rho > a.max_spearman:
bad.append(f"Spearman(position, KL) {rho:.3f} > {a.max_spearman}: KL rises with position (a leaking state); "
f"a negative correlation is not drift")
if bad:
print("GATE FAILED: " + "; ".join(bad))
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+179
View File
@@ -0,0 +1,179 @@
// tools/qwen36_teacher_llama.cpp - llama.cpp's own greedy continuation of a prompt, with the head's logits at every
// generated position and the routed experts at probed layers: the reference the Qwen3.6 runner is held to on the real
// files (docs/qwen36-port/step4-runner.md; the comparison is tools/qwen36_compare_logits.py).
//
// Build against a llama.cpp build of the pinned submodule (CUDA or CPU), e.g. on VM 221:
// c++ -std=c++17 -O1 tools/qwen36_teacher_llama.cpp -o qwen36-teacher -I$LL/include -I$LL/ggml/include \
// $B/src/libllama.a $B/ggml/src/libggml.a $B/ggml/src/libggml-cpu.a $B/ggml/src/ggml-cuda/libggml-cuda.a \
// $B/ggml/src/libggml-base.a -lcudart -lcublas -lcublasLt -lcuda -lgomp -lpthread -ldl -lm
//
// qwen36-teacher MODEL.gguf OUTDIR --prompt-file FILE [--n-gen 64] [--ngl 99] [--ctx 8192] [--probe 0,3,20,39]
// qwen36-teacher MODEL.gguf --detok FILE the ids in FILE (commas or whitespace) as text, to stdout
//
// Writes OUTDIR/prompt_ids.txt (the prompt's token ids, parse_special on: the ChatML tags of the regina prompts are
// tokens), OUTDIR/continuation.txt (the N greedy tokens), OUTDIR/logits.f32 (N rows of n_vocab F32: row j is the
// distribution the j-th generated token was picked from, i.e. the position n_prompt - 1 + j), OUTDIR/meta.txt
// ("n_vocab N n_prompt P n_gen G"), OUTDIR/routes.txt ("<row> <layer> e0 .. e7" for the probed layers of every
// generated row; the prompt batch is not traced) and OUTDIR/text.txt (the continuation as text). Greedy means the
// argmax of the F32 logits; the KV cache is F16 as the engine's --kv fp16 is.
#include "llama.h"
#include "ggml.h"
#include "ggml-backend.h"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <set>
#include <sstream>
#include <string>
#include <vector>
#include <sys/stat.h>
namespace {
struct Routes {
std::set<int> probe;
FILE* out = nullptr;
int row = -1; // the generated row being decoded (-1: the prompt batch, not traced)
};
bool cb_routes(struct ggml_tensor* t, bool ask, void* ud) {
if (ask) return true;
auto* r = (Routes*) ud;
if (r->row < 0 || r->out == nullptr || std::strncmp(t->name, "ffn_moe_topk-", 13) != 0) return true;
const int layer = std::atoi(t->name + 13);
if (!r->probe.count(layer) || t->type != GGML_TYPE_I32) return true;
const int64_t k = t->ne[0], n = t->ne[1];
std::vector<int32_t> ids((size_t) (k * n));
ggml_backend_tensor_get(t, ids.data(), 0, ids.size() * sizeof(int32_t));
for (int64_t i = 0; i < n; ++i) {
std::fprintf(r->out, "%d %d", r->row, layer);
for (int64_t j = 0; j < k; ++j) std::fprintf(r->out, " %d", ids[(size_t) (i * k + j)]);
std::fprintf(r->out, "\n");
}
return true;
}
std::vector<llama_token> read_ids(const std::string& path) {
std::ifstream in(path);
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
for (char& c : text) if (c == ',') c = ' ';
std::istringstream is(text);
std::vector<llama_token> v;
for (long long x; is >> x;) v.push_back((llama_token) x);
return v;
}
std::string piece(const llama_vocab* vocab, llama_token t) {
char buf[512];
const int n = llama_token_to_piece(vocab, t, buf, sizeof buf, 0, true);
return n > 0 ? std::string(buf, (size_t) n) : std::string();
}
} // namespace
int main(int argc, char** argv) {
if (argc < 3) {
std::fprintf(stderr, "usage: %s MODEL.gguf OUTDIR --prompt-file FILE [--n-gen N] [--ngl N] [--ctx N] [--probe L,L,..]\n"
" %s MODEL.gguf --detok FILE\n", argv[0], argv[0]);
return 1;
}
const std::string model_path = argv[1];
std::string outdir, prompt_file, detok;
int n_gen = 64, ngl = 99, n_ctx = 8192;
std::set<int> probe = {0, 3, 20, 39};
for (int i = 2; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> const char* { if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", a.c_str()); std::exit(1); } return argv[++i]; };
if (a == "--prompt-file") prompt_file = next();
else if (a == "--n-gen") n_gen = std::atoi(next());
else if (a == "--ngl") ngl = std::atoi(next());
else if (a == "--ctx") n_ctx = std::atoi(next());
else if (a == "--detok") detok = next();
else if (a == "--probe") {
probe.clear();
std::string s = next();
for (char& c : s) if (c == ',') c = ' ';
std::istringstream is(s);
for (int l; is >> l;) probe.insert(l);
} else if (outdir.empty()) outdir = a;
else { std::fprintf(stderr, "unknown argument %s\n", a.c_str()); return 1; }
}
llama_backend_init();
llama_model_params mp = llama_model_default_params();
mp.n_gpu_layers = detok.empty() ? ngl : 0;
llama_model* model = llama_model_load_from_file(model_path.c_str(), mp);
if (!model) { std::fprintf(stderr, "model load failed\n"); return 1; }
const llama_vocab* vocab = llama_model_get_vocab(model);
if (!detok.empty()) {
for (llama_token t : read_ids(detok)) std::fputs(piece(vocab, t).c_str(), stdout);
std::fputc('\n', stdout);
llama_model_free(model);
llama_backend_free();
return 0;
}
if (outdir.empty() || prompt_file.empty()) { std::fprintf(stderr, "OUTDIR and --prompt-file are required\n"); return 1; }
mkdir(outdir.c_str(), 0755);
std::ifstream pf(prompt_file);
std::string prompt((std::istreambuf_iterator<char>(pf)), std::istreambuf_iterator<char>());
while (!prompt.empty() && prompt.back() == '\n') prompt.pop_back(); // the files end in one newline the prompt does not
std::vector<llama_token> toks(prompt.size() + 16);
int n = llama_tokenize(vocab, prompt.c_str(), (int32_t) prompt.size(), toks.data(), (int32_t) toks.size(), false, true);
if (n < 0) { toks.resize((size_t) -n); n = llama_tokenize(vocab, prompt.c_str(), (int32_t) prompt.size(), toks.data(), (int32_t) toks.size(), false, true); }
if (n <= 0) { std::fprintf(stderr, "tokenize failed\n"); return 1; }
toks.resize((size_t) n);
const int n_vocab = llama_vocab_n_tokens(vocab);
Routes routes;
routes.probe = probe;
routes.out = std::fopen((outdir + "/routes.txt").c_str(), "w");
llama_context_params cp = llama_context_default_params();
cp.n_ctx = (uint32_t) n_ctx;
cp.n_batch = cp.n_ubatch = 2048;
cp.type_k = GGML_TYPE_F16;
cp.type_v = GGML_TYPE_F16;
cp.cb_eval = cb_routes;
cp.cb_eval_user_data = &routes;
llama_context* ctx = llama_init_from_model(model, cp);
if (!ctx) { std::fprintf(stderr, "context init failed\n"); return 1; }
// the prompt, logits for its last position only
routes.row = -1;
for (int i = 0; i < n; i += 2048) {
const int m = std::min(2048, n - i);
if (llama_decode(ctx, llama_batch_get_one(toks.data() + i, m))) { std::fprintf(stderr, "prompt decode failed\n"); return 1; }
}
FILE* lf = std::fopen((outdir + "/logits.f32").c_str(), "wb");
std::vector<llama_token> gen;
std::string text;
for (int j = 0; j < n_gen; ++j) {
const float* lg = llama_get_logits_ith(ctx, -1);
if (lg == nullptr) { std::fprintf(stderr, "no logits at row %d\n", j); return 1; }
std::fwrite(lg, sizeof(float), (size_t) n_vocab, lf);
const llama_token t = (llama_token) (std::max_element(lg, lg + n_vocab) - lg);
gen.push_back(t);
text += piece(vocab, t);
if (j + 1 == n_gen) break;
routes.row = j + 1; // the next decode's logits are row j + 1
llama_token one = t;
if (llama_decode(ctx, llama_batch_get_one(&one, 1))) { std::fprintf(stderr, "decode failed at row %d\n", j + 1); return 1; }
}
std::fclose(lf);
std::fclose(routes.out);
{
std::ofstream o(outdir + "/prompt_ids.txt");
for (size_t i = 0; i < toks.size(); ++i) o << (i ? "," : "") << toks[i];
o << "\n";
std::ofstream c(outdir + "/continuation.txt");
for (size_t i = 0; i < gen.size(); ++i) c << (i ? "," : "") << gen[i];
c << "\n";
std::ofstream m(outdir + "/meta.txt");
m << "n_vocab " << n_vocab << " n_prompt " << n << " n_gen " << gen.size() << "\n";
std::ofstream tx(outdir + "/text.txt");
tx << text << "\n";
}
std::printf("%s: %d prompt tokens, %zu greedy tokens, logits %zu x %d in %s\n", prompt_file.c_str(), n, gen.size(),
gen.size(), n_vocab, outdir.c_str());
std::printf("---\n%s\n---\n", text.c_str());
llama_free(ctx);
llama_model_free(model);
llama_backend_free();
return 0;
}