File size: 6,476 Bytes
272005d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""eval/agentic-<name>: the agentic measurement corpus in a model's own markup, through its chat template.

    FOUNDRY_MODEL_DIR=/path/to/tokenizer python tools/build_eval_auto.py --name kolibri \\
        --tokenizer /path/to/tokenizer.json --build builds/kolibri-1-moe --raw-eval /path/to/raw_eval

eval/agentic is rendered in Muse Glimmer markup, which is plain text to any
other tokenizer. This renders the same generator (tools/gen_agentic_eval.py:
its own tools, prompts and prose, nothing shared with the calibration agentic
slice; 120 scripted conversations and up to 900 grounded in the held-out
repositories, as build_eval.py draws them) with tools/auto_fmt.py, so the conversations carry the target's special
tokens, its tool-call format and its reasoning switch (reasoning_effort per
conversation).

Exclusion as in build_eval.py: a conversation enters only if it shares no
13-gram with the calibration build (calib_train and calib_longctx) or with the
other eval corpora; the template's own scaffolding is subtracted first, since
it is in every conversation the model ever sees. llama-perplexity has to read
the result with --parse-special (node_base passes it when the build has it) or
the markup is scored as literal characters.
"""

from __future__ import annotations

import argparse
import glob
import json
import os
import sys
from collections import Counter

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import auto_fmt as F  # noqa: E402
import build_eval as BE  # noqa: E402
import gen_agentic_eval as GAE  # noqa: E402
import poollib as P  # noqa: E402

# build_eval.py's grounding set: repositories that appear in no other file. The four scripted
# scenarios alone repeat themselves (92% duplicate lines, 0.4% of the vocabulary on Kolibri-1).
GROUNDING_REPOS = ("rust-regex", "googletest", "black", "tokio-bytes")


def grounding_pool(raw_eval):
    """The held-out repository files, as build_eval.py reads them (its legacy `sources.walk_repo`)."""
    import subprocess
    sys.path.insert(0, os.path.join(P.REPO_ROOT, "builds", "dsv4-flash-0731", "pipeline"))
    import sources as S
    docs, commits = [], {}
    for repo in GROUNDING_REPOS:
        root = os.path.join(raw_eval, repo)
        if not os.path.isdir(root):
            raise SystemExit(f"missing grounding clone: {root} ({BE.EXTRA_EVAL_REPOS[repo][0]})")
        commits[repo] = subprocess.run(["git", "-C", root, "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()
        url, lic = BE.EXTRA_EVAL_REPOS[repo]
        for rel, lang, text in sorted(S.walk_repo(root, repo), key=lambda t: t[0]):
            docs.append({"id": P.make_id(repo, rel, text), "source": repo, "path": rel, "license": lic, "lang": lang,
                         "origin": "repo_file", "text": text, "upstream": url})
    return docs, commits


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--name", required=True, help="eval/agentic-<name>")
    ap.add_argument("--tokenizer", required=True)
    ap.add_argument("--build", required=True, help="the calibration build this eval must not overlap")
    ap.add_argument("--n", type=int, default=120, help="scripted candidate conversations")
    ap.add_argument("--grounded", type=int, default=900, help="conversations grounded in held-out repository files")
    ap.add_argument("--raw-eval", required=True, help="clones of the grounding repositories (tools/clone.sh)")
    ap.add_argument("--seed", type=int, default=20261006)
    ap.add_argument("--repo", default=P.REPO_ROOT)
    a = ap.parse_args()

    tok = P.TargetTokenizer(a.tokenizer)
    pool, commits = grounding_pool(a.raw_eval)
    convs = GAE.build(a.n, a.seed) + GAE.build_grounded(pool, min(len(pool), a.grounded), a.seed + 4)
    print(f"{len(convs)} candidate conversations ({len(pool)} held-out files for grounding)")
    render = lambda c: F.render(c["messages"], tools=c["tools"], reasoning_strength=c["reasoning_strength"],  # noqa: E731
                                add_bos=False, reasoning_effort=True)
    # the template's scaffolding, as build_eval subtracts it: an empty turn with every tool set used
    scaffolds = {F.render([{"role": "user", "content": ""}], tools=c["tools"], reasoning_strength=lvl, reasoning_effort=True)
                 for c in convs for lvl in ("none", "low", "high")}
    ignore = {int(x) for s in scaffolds for x in P.shingles(s, BE.NGRAM)}
    excl = BE.Excluder(ignore)
    for f in ("calib_train.txt", "calib_longctx.txt"):
        p = os.path.join(a.build, f)
        if os.path.exists(p):
            excl.add_static(open(p, encoding="utf-8").read(), f)
    # eval/agentic is this same generator in another model's markup: overlapping it is the point of a re-render
    for p in sorted(glob.glob(os.path.join(a.repo, "eval", "*", "eval_*.txt"))):
        if f"agentic-{a.name}" not in p and os.sep + os.path.join("eval", "agentic") + os.sep not in p:
            excl.add_static(open(p, encoding="utf-8").read(), os.path.relpath(p, a.repo))
    excl.freeze()

    docs = []
    for c in convs:
        text = render(c)
        docs.append({"id": P.make_id("eval-agentic", f"{c['scenario']}/{c['index']}", text),
                     "source": f"synthetic/eval-agentic:{c['scenario']}",
                     "path": f"eval_agentic/{c['scenario']}/{c['index']:04d}",
                     "license": "CC0-1.0 (generated; quoted file excerpts keep their upstream licence)",
                     "lang": "chat", "origin": "synth_agentic_eval", "text": text,
                     "grounded_in": c.get("grounded_in", ""), "reasoning_strength": c["reasoning_strength"]})
    out_dir = os.path.join(a.repo, "eval", f"agentic-{a.name}")
    taken, n = BE.take_until(docs, excl, tok, BE.TARGET_LO, BE.TARGET_HI, f"eval/agentic-{a.name}", allow_intra_repeat=True)
    path = os.path.join(out_dir, f"eval_agentic-{a.name}.txt")
    BE.write_corpus(path, taken, os.path.join(out_dir, f"eval_agentic-{a.name}.manifest.jsonl"))
    with open(os.path.join(out_dir, "grounding.json"), "w") as f:
        json.dump({"repositories": commits, "seed": a.seed}, f, indent=1)
    print(f"{path}: {len(taken)} conversations, {n:,} tokens, {n // BE.CTX} chunks of {BE.CTX}; "
          f"reasoning {dict(Counter(d['reasoning_strength'] for d, _, _ in taken))}")
    return 0


if __name__ == "__main__":
    sys.exit(main())