File size: 6,449 Bytes
9d6c277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
"""MRCR (openai/mrcr, 2-needle) for the KV-cache study: prepare, run, score.

  python mrcr.py prep                         # -> ~/bench/data/mrcr_2n.jsonl (token bins 8K..256K)
  python mrcr.py run RUN PORT                 # -> ~/bench/mrcr/RUN.jsonl (resumable)
  python mrcr.py score [RUN ...]              # per-bin scores + paired diffs vs baseline
Other models: KVQ_TOK=<model dir> KVQ_DATA=<data folder> KVQ_MRCR_OUT=<results folder> under ~/bench,
KVQ_EXTRA_BODY=<JSON request extras> (defaults: Qwen3.8-27B, data, mrcr, {"reasoning_effort": "low"}).

Grading is the official one: 0 if the answer does not start with random_string_to_prepend,
else difflib.SequenceMatcher (response left-stripped: the reasoning parser leaves leading newlines) ratio of answer vs gold (with the prefix stripped from both).
"""
import asyncio
import json
import os
import random
import sys
from difflib import SequenceMatcher
from pathlib import Path

B = Path.home() / "bench"
DATA = B / os.environ.get("KVQ_DATA", "data") / "mrcr_2n.jsonl"
MODEL = Path(os.environ.get("KVQ_TOK", Path.home() / "models" / "Qwen3.8-27B"))
RES = B / os.environ.get("KVQ_MRCR_OUT", "mrcr")
EXTRA_BODY = json.loads(os.environ.get("KVQ_EXTRA_BODY", '{"reasoning_effort": "low"}'))
BINS = [(8192, 16384), (16384, 32768), (32768, 65536), (65536, 131072), (131072, 245760)]
MAX_TOKENS = 16384  # input (<=245760) + output must fit max-model-len 262144
CONC = {16384: 64, 32768: 32, 65536: 16, 131072: 8, 245760: 4}  # by bin upper edge, sized to bf16 KV pool
PAIRS = [("BF16-FI", "BF16", "kernel effect"), ("FP8", "BF16", "FP8 KV effect"), ("FP4", "BF16-FI", "NVFP4 KV effect")]


def binname(hi):
    return f"{hi // 1024}K"


def prep():
    import pandas as pd
    from transformers import AutoTokenizer
    tok = AutoTokenizer.from_pretrained(MODEL)
    d = B / "data" / "mrcr" / "2needle"
    df = pd.concat([pd.read_parquet(d / f"2needle_{i}.parquet") for i in (0, 1)]).reset_index(drop=True)
    df = df[df.n_chars < 1.3e6]
    out = []
    for i, r in df.iterrows():
        msgs = json.loads(r.prompt)
        n = len(tok(tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)).input_ids)
        for lo, hi in BINS:
            if lo < n <= hi:
                out.append({"id": int(i), "bin": binname(hi), "n_tokens": n, "messages": msgs, "answer": r.answer,
                            "prefix": r.random_string_to_prepend})
    out.sort(key=lambda x: x["n_tokens"])
    with open(DATA, "w") as f:
        for x in out:
            f.write(json.dumps(x) + "\n")
    for lo, hi in BINS:
        print(binname(hi), sum(x["bin"] == binname(hi) for x in out))
    print("wrote", DATA, len(out))


def grade(response, answer, prefix):
    response = response.lstrip()  # reasoning parser leaves "\n\n" after </think>
    if not response.startswith(prefix):
        return 0.0
    return SequenceMatcher(None, response.removeprefix(prefix), answer.removeprefix(prefix)).ratio()


async def run(name, port):
    from openai import AsyncOpenAI
    cli = AsyncOpenAI(base_url=f"http://localhost:{port}/v1", api_key="dummy", timeout=7200, max_retries=0)
    model = (await cli.models.list()).data[0].id
    rows = [json.loads(l) for l in open(DATA)]
    out = RES / f"{name}.jsonl"
    out.parent.mkdir(exist_ok=True)
    done = {r["id"] for l in open(out) if not (r := json.loads(l))["error"]} if out.exists() else set()  # errored rows are retried
    lock = asyncio.Lock()

    async def one(r, sem):
        async with sem:
            try:
                c = await cli.chat.completions.create(model=model, messages=r["messages"], temperature=0,
                                                      max_tokens=MAX_TOKENS, seed=0,
                                                      extra_body=EXTRA_BODY)
                text, err, fin, ntok = c.choices[0].message.content or "", None, c.choices[0].finish_reason, c.usage.completion_tokens
            except Exception as e:
                text, err, fin, ntok = "", repr(e)[:300], None, 0
            rec = {"id": r["id"], "bin": r["bin"], "n_tokens": r["n_tokens"], "score": grade(text, r["answer"], r["prefix"]),
                   "finish": fin, "out_tokens": ntok, "error": err, "response": text}
            async with lock:
                with open(out, "a") as f:
                    f.write(json.dumps(rec) + "\n")

    for lo, hi in BINS:
        todo = [r for r in rows if r["bin"] == binname(hi) and r["id"] not in done]
        print(f"== {name} bin {binname(hi)}: {len(todo)} to run, conc {CONC[hi]}", flush=True)
        sem = asyncio.Semaphore(CONC[hi])
        await asyncio.gather(*(one(r, sem) for r in todo))
    print(f"MRCR_DONE {name}", flush=True)


def load(name):
    f = RES / f"{name}.jsonl"
    return {(r := json.loads(l))["id"]: r for l in open(f)} if f.exists() else None


def paired_ci(d, iters=10000, seed=0):
    rng, n = random.Random(seed), len(d)
    m = sorted(sum(d[rng.randrange(n)] for _ in range(n)) / n for _ in range(iters))
    return sum(d) / n, m[int(0.025 * iters)], m[int(0.975 * iters)]


def score(names):
    names = names or sorted(p.stem for p in RES.glob("*.jsonl"))
    bins = [binname(hi) for _, hi in BINS]
    print("MRCR 2-needle, mean score x100 (n, errors)")
    print(f"{'run':<10}" + "".join(f"{b:>16}" for b in bins) + f"{'all':>16}")
    for nm in names:
        R = load(nm)
        line = f"{nm:<10}"
        for b in bins + ["all"]:
            v = [r for r in R.values() if b == "all" or r["bin"] == b]
            e = sum(1 for r in v if r["error"])
            line += f"{100 * sum(r['score'] for r in v) / max(len(v), 1):>8.2f} ({len(v)},{e})".rjust(16)
        print(line)
    print("\nPaired differences (treatment - baseline, points), 95% bootstrap CI")
    for t, base, label in PAIRS:
        T, Bs = load(t), load(base)
        if not T or not Bs:
            continue
        for b in bins + ["all"]:
            ids = [i for i in T if i in Bs and (b == "all" or T[i]["bin"] == b)]
            if ids:
                m, lo, hi = paired_ci([T[i]["score"] - Bs[i]["score"] for i in ids])
                print(f"{label:<16} {t:>8} vs {base:<8} {b:>5}  {100 * m:+6.2f}  [{100 * lo:+6.2f}, {100 * hi:+6.2f}]  n={len(ids)}")


if __name__ == "__main__":
    cmd = sys.argv[1]
    if cmd == "prep":
        prep()
    elif cmd == "run":
        asyncio.run(run(sys.argv[2], sys.argv[3]))
    else:
        score(sys.argv[2:])