File size: 7,768 Bytes
6f2ed01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/env python
"""Stage VI -> outputs/evaluation/<model>.jsonl   [GPU]

Runs the full evaluation query bank for ONE model. Same decoding configuration
as anchor qualification (configs/models.yaml:generation) so that anchor and
perturbation numbers are directly comparable -- a different max_new_tokens or a
chat template on one side would turn a protocol difference into a fake
stability effect.

Anchor queries live in the bank too (condition_family == "anchor") and share
their prompt string with qualification_run.py. They are regenerated here rather
than copied so that every condition passes through one identical code path.

Scoring is NOT done here: eval_score.py reads these generations on CPU, so the
scorer can be revised without paying for GPU again.
"""
import os, sys, json, time, argparse, collections
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from common import load_config, out_path, data_path, read_jsonl

PROMPT = "Question: {q}\nAnswer with only the shortest correct answer.\nAnswer:"


def build_prompt(row):
    """Anchor and the open-ended conditions get the standard instruction wrapper.

    The perturbation queries carry their own surface form -- that IS the
    perturbation -- so wrapping them in the anchor template would erase the
    manipulation. They are passed through with a bare "Answer:" cue so the model
    still knows a short answer is wanted.
    """
    fam = row["condition_family"]
    if fam == "anchor":
        return PROMPT.format(q=row["query"])
    if fam == "recognition":
        # candidates are already inside the query text
        return f"{row['query']}\nAnswer:"
    return f"{row['query']}\nAnswer:"


def resolve_weights(explicit, cfg, entry):
    """--model-path, then $FKS_MODELS/<path>, then models.yaml:model_root, then the hub id.

    Only the hub id travels between machines, so it is the documented default;
    the two local options exist so an offline cluster does not have to edit a
    tracked config.
    """
    if explicit:
        return explicit
    root = os.environ.get("FKS_MODELS") or cfg.get("model_root")
    if root:
        local = os.path.join(root, entry.get("path", entry["name"]))
        if os.path.isdir(local):
            return local
    if entry.get("hf"):
        return entry["hf"]
    raise SystemExit(
        f"cannot locate weights for {entry['name']}: pass --model-path, set "
        f"FKS_MODELS, or add an `hf:` id to configs/models.yaml")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model", required=True, help="name from configs/models.yaml")
    ap.add_argument("--model-path", default=None,
                    help="local weights directory or hub id; overrides models.yaml")
    ap.add_argument("--queries", default=data_path("evaluation_queries_44416.jsonl"))
    ap.add_argument("--conditions", nargs="*", default=None,
                    help="restrict to these condition families (default: all)")
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--batch", type=int, default=0, help="0 = value from config")
    ap.add_argument("--resume", action="store_true",
                    help="skip queries already present in the output file")
    args = ap.parse_args()

    cfg = load_config("models.yaml")
    entry = next((m for m in cfg["evaluated_models"] if m["name"] == args.model), None)
    if entry is None:
        raise SystemExit(f"{args.model} is not in configs/models.yaml:evaluated_models")
    gen_cfg = cfg["generation"]
    if gen_cfg.get("use_chat_template"):
        raise SystemExit("spec 7.2: base and instruct models must share the raw "
                         "prompt string; chat templates are not applied")

    rows = list(read_jsonl(args.queries))
    if args.conditions:
        rows = [r for r in rows if r["condition_family"] in args.conditions]
    if args.limit:
        rows = rows[:args.limit]

    dest = out_path("evaluation", f"{args.model}.jsonl")
    done = set()
    if args.resume and os.path.exists(dest):
        done = {r["query_id"] for r in read_jsonl(dest)}
        rows = [r for r in rows if r["query_id"] not in done]
        print(f"[{args.model}] resuming: {len(done)} already done", flush=True)
    if not rows:
        print(f"[{args.model}] nothing to do")
        return

    N = len(rows)
    fam_counts = collections.Counter(r["condition_family"] for r in rows)
    print(f"[{args.model}] N={N}  {dict(fam_counts)}", flush=True)

    path = resolve_weights(args.model_path, cfg, entry)
    print(f"[{args.model}] weights: {path}", flush=True)
    torch.manual_seed(gen_cfg.get("seed", 0))
    tok = AutoTokenizer.from_pretrained(path)
    if tok.pad_token is None:
        tok.pad_token = tok.eos_token
    tok.padding_side = "left"
    tok.truncation_side = "left"
    model = AutoModelForCausalLM.from_pretrained(
        path, dtype=getattr(torch, gen_cfg.get("dtype", "bfloat16")),
        device_map={"": 0}).eval()

    prompts = [build_prompt(r) for r in rows]
    # context queries prepend distractor sentences, so they are much longer than
    # the anchor; a single global max_len would silently truncate them
    max_len = max(gen_cfg.get("max_prompt_len", 96), 192)
    B = args.batch or gen_cfg.get("batch_size", 96)

    out = [None] * N
    order = sorted(range(N), key=lambda i: len(prompts[i]))
    t0 = time.time()
    with torch.no_grad():
        for b in range(0, N, B):
            idx = order[b:b + B]
            enc = tok([prompts[i] for i in idx], return_tensors="pt", padding=True,
                      truncation=True, max_length=max_len).to(0)
            plen = enc["input_ids"].shape[1]
            gen = model.generate(**enc,
                                 max_new_tokens=gen_cfg.get("max_new_tokens", 24),
                                 do_sample=gen_cfg.get("do_sample", False),
                                 num_beams=gen_cfg.get("num_beams", 1),
                                 pad_token_id=tok.pad_token_id)
            new_ids = gen[:, plen:]
            texts = tok.batch_decode(new_ids, skip_special_tokens=True)
            for j, i in enumerate(idx):
                ids = new_ids[j].tolist()
                n_tok, fin = len(ids), "length"
                for k, t in enumerate(ids):
                    if t == tok.eos_token_id:
                        n_tok, fin = k, "eos"
                        break
                out[i] = {"query_id": rows[i]["query_id"],
                          "fact_id": rows[i]["fact_id"],
                          "condition_family": rows[i]["condition_family"],
                          "model": args.model,
                          "prompt": prompts[i],
                          "raw_response": texts[j],
                          "generated_tokens": int(n_tok),
                          "finish_reason": fin}
            if b % (B * 20) == 0:
                d = b + len(idx)
                print(f"  {d}/{N}  {d / max(time.time() - t0, 1e-9):.1f}/s", flush=True)

    mode = "a" if (args.resume and done) else "w"
    with open(dest, mode) as f:
        for r in out:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")
    json.dump({"model": args.model, "n_generated": N, "resumed_from": len(done),
               "generation": gen_cfg, "max_prompt_len": max_len,
               "model_entry": entry, "seconds": round(time.time() - t0, 1),
               "by_condition": dict(fam_counts)},
              open(out_path("evaluation", f"{args.model}.meta.json"), "w"),
              indent=2, ensure_ascii=False)
    print(f"[{args.model}] wrote {N} -> {dest}  ({time.time() - t0:.0f}s)  EVAL_DONE")


if __name__ == "__main__":
    main()