oBunny-1.1 / code /passkey_docs.py
Leporidae's picture
oBunny-1.1 release: base model with the attention retune, 4K context
12a2867 verified
Raw History Blame Contribute Delete
4.74 kB
"""Passkey retrieval with VARIED real haystacks (11-30, for the oBunny-1.1 card). longctx_eval.py's "real" haystack is
one 20K-token window of ONE document (heldout_long doc 0, a generated neovim API header full of key/keymap names),
which flattered surgery v3 badly. Here every case takes its haystack from a different held-out document (prose and
code alternating, docs 12+ so none is the old pool or a loss document). Same prefix, needle, question and scoring as
longctx_eval (correct = every answer token is the top choice = greedy generation writes the key).
Usage: python passkey_docs.py [models=runs/base_1b/model.pt,runs/surgery_pilot/model.pt] [lengths=2048,3072,4096,6144,8192]
[depths=0.1,0.3,0.5,0.7,0.9] [trials=20] [device=cuda] [out=runs/passkey_docs]
Model specs take longctx_eval's variants, e.g. runs/surgery_pilot/model.pt@w4096 (long window cut to 4096).
"""
import gzip, json, os, random, sys, time
import torch
from tokenizers import Tokenizer
import longctx_eval as le
BINS = [0, 1024, 2048, 3072, 4096, 5120, 6144, 7680]
def main():
args = dict(a.split("=", 1) for a in sys.argv[1:])
models = args.get("models", "runs/base_1b/model.pt,runs/surgery_pilot/model.pt").split(",")
lengths = [int(x) for x in args.get("lengths", "2048,3072,4096,6144,8192").split(",")]
depths = [float(x) for x in args.get("depths", "0.1,0.3,0.5,0.7,0.9").split(",")]
trials = int(args.get("trials", 20))
device = torch.device(args.get("device", "cuda"))
out = args.get("out", "runs/passkey_docs")
os.makedirs(out, exist_ok=True)
T = (max(lengths) + 127) // 128 * 128
tok = Tokenizer.from_file("data/tokenizers/mix32768.json")
own, rep = [], []
with gzip.open(le.HELDOUT, "rt", encoding="utf-8") as f:
for i, line in enumerate(f):
r = json.loads(line)
if i >= 12 and r["tokens"] >= max(lengths) + 512:
(own if r["source"] == "owndocs" else rep).append((i, r["source"], tok.encode(r["text"]).ids))
docs = [d for pair in zip(own, rep) for d in pair] # alternate prose / code
docs = docs[:max(trials, 2)]
rng = random.Random(int(args.get("seed", 2026)))
cases = []
for L in lengths:
for d in depths:
for t in range(trials):
di, src, ids = docs[t % len(docs)]
key = rng.randrange(10000, 100000)
full, n_ans = le.passkey_case(tok, L, d, key, "real", rng, ids)
needle = tok.encode(le.NEEDLE.format(key=key)).ids
at = next(p for p in range(len(full)) if full[p:p + len(needle)] == needle)
cases.append(dict(hay=src, doc=di, length=L, depth=d, key=key, ids=full, n_ans=n_ans,
back=len(full) - n_ans - at)) # tokens from the needle to the answer
print(f"{len(cases)} cases, haystacks from {len(docs)} documents ({sum(s == 'owndocs' for _, s, _ in docs)} prose, "
f"{sum(s == 'repos' for _, s, _ in docs)} code); fixed length {T}", flush=True)
summary = dict(time=time.strftime("%Y-%m-%d %H:%M:%S"), lengths=lengths, depths=depths, trials=trials,
docs=[d[0] for d in docs], bins=BINS, models={})
with open(os.path.join(out, "cases.jsonl"), "w", encoding="utf-8") as f:
for m in models:
rows, _ = le.run_model(m, args, cases, [], device, T)
res = {}
for r, c in zip(rows, cases):
r.update(doc=c["doc"], back=c["back"])
f.write(json.dumps(r) + "\n")
b = min(max(k for k in range(len(BINS) - 1) if c["back"] >= BINS[k]), len(BINS) - 2)
for key in (f"{BINS[b]}-{BINS[b + 1]}", f"{c['hay']}:{BINS[b]}-{BINS[b + 1]}", f"L{c['length']}"):
s = res.setdefault(key, [0, 0])
s[0] += r["correct"]; s[1] += 1
summary["models"][m] = {k: dict(correct=v[0], n=v[1]) for k, v in res.items()}
with open(os.path.join(out, "summary.json"), "w", encoding="utf-8") as f:
json.dump(summary, f, indent=1)
labels = [f"{BINS[k]}-{BINS[k + 1]}" for k in range(len(BINS) - 1)]
print("\nexact recall by distance back (tokens), varied haystacks")
print(f"{'':44s}" + "".join(f"{x:>11s}" for x in labels))
for m, s in summary["models"].items():
for pre, name in (("", "all"), ("owndocs:", "prose"), ("repos:", "code")):
cells = [s.get(pre + x) for x in labels]
print(f"{m[-38:]:38s} {name:5s}" + "".join(f"{c['correct']:>5d}/{c['n']:<5d}" if c else f"{'-':>11s}"
for c in cells))
print(f"\nsaved {out}/summary.json")
if __name__ == "__main__":
main()