betterwithage commited on
Commit
d8663fc
·
verified ·
1 Parent(s): 046f977

fix: generate_plan tok.decode batch bug -> batch_decode; prior fp16 scores void

Browse files
Files changed (1) hide show
  1. szl_khipu_eval.py +279 -0
szl_khipu_eval.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """KHIPU-R2 held-out eval — exact port of eval_khipu.py scoring.
2
+
3
+ Runs the committed held-out set (eval.jsonl: 5 navigate, adversarial.jsonl: 6)
4
+ against a merged KHIPU-R2 checkpoint in fp16, optionally also in 4-bit NF4,
5
+ so abstain counts are apples-to-apples with the hub MEASURED 3/6 baseline
6
+ (which ran on the 4-bit Unsloth runtime, temperature 0).
7
+
8
+ Curriculum is fetched from the Hub (SZL-Khipu-1.5B/repro/) and sha256-checked
9
+ against its MANIFEST.json when a digest is declared. Held-out files read-only.
10
+
11
+ Usage:
12
+ python szl_khipu_eval.py --model merged/KHIPU-R2
13
+ python szl_khipu_eval.py --model merged/KHIPU-R2 --compare-4bit --out reports/khipu_4bit_comparison.json
14
+ """
15
+ import argparse
16
+ import gc
17
+ import hashlib
18
+ import json
19
+ import platform
20
+ import re
21
+ import time
22
+ from datetime import datetime, timezone
23
+ from pathlib import Path
24
+
25
+ import torch
26
+ from huggingface_hub import hf_hub_download
27
+ from jsonschema.validators import validator_for
28
+ from transformers import AutoModelForCausalLM, AutoTokenizer
29
+
30
+ HUB = "SZLHOLDINGS/SZL-Khipu-1.5B"
31
+ CURRICULUM = ["repro/eval.jsonl", "repro/adversarial.jsonl", "repro/khipu.schema.json", "repro/MANIFEST.json"]
32
+
33
+
34
+ def sha256_file(path):
35
+ h = hashlib.sha256()
36
+ with open(path, "rb") as f:
37
+ for chunk in iter(lambda: f.read(1 << 20), b""):
38
+ h.update(chunk)
39
+ return h.hexdigest()
40
+
41
+
42
+ def manifest_files_index(manifest):
43
+ """Return {name: entry} whether MANIFEST stores files as a dict or a list."""
44
+ if isinstance(manifest, dict):
45
+ raw = manifest.get("files", [])
46
+ elif isinstance(manifest, list):
47
+ raw = manifest
48
+ else:
49
+ raw = []
50
+ if isinstance(raw, dict):
51
+ return dict(raw)
52
+ index = {}
53
+ for e in raw:
54
+ if isinstance(e, dict):
55
+ key = e.get("name") or e.get("path") or e.get("file")
56
+ if key:
57
+ index[key] = e
58
+ return index
59
+
60
+
61
+ def fetch_curriculum(workdir):
62
+ workdir = Path(workdir)
63
+ workdir.mkdir(parents=True, exist_ok=True)
64
+ local = {}
65
+ for name in CURRICULUM:
66
+ cached = hf_hub_download(repo_id=HUB, filename=name, repo_type="model")
67
+ dest = workdir / Path(name).name
68
+ dest.write_bytes(Path(cached).read_bytes())
69
+ local[Path(name).name] = dest
70
+ manifest = json.loads(local["MANIFEST.json"].read_text(encoding="utf-8"))
71
+ files_meta = manifest_files_index(manifest)
72
+ for name in ["eval.jsonl", "adversarial.jsonl", "khipu.schema.json"]:
73
+ actual = sha256_file(local[name])
74
+ entry = files_meta.get(name) or files_meta.get("repro/" + name) or {}
75
+ declared = entry.get("sha256") if isinstance(entry, dict) else entry
76
+ if declared is None:
77
+ print(f"[khipu-eval] WARNING: no manifest digest for {name}; actual sha256={actual}")
78
+ elif declared != actual:
79
+ raise SystemExit(f"sha256 mismatch for {name}: {actual} != manifest {declared}")
80
+ else:
81
+ print(f"[khipu-eval] {name}: digest verified")
82
+ print("[khipu-eval] curriculum fetched")
83
+ return local
84
+
85
+
86
+ def load_jsonl(path):
87
+ return [json.loads(l) for l in Path(path).read_text(encoding="utf-8").splitlines() if l.strip()]
88
+
89
+
90
+ def extract_json(text):
91
+ text = (text or "").strip()
92
+ if text.startswith("```"):
93
+ text = re.sub(r"^```(?:json)?\s*", "", text)
94
+ text = re.sub(r"\s*```$", "", text)
95
+ try:
96
+ return json.loads(text)
97
+ except Exception:
98
+ pass
99
+ start = text.find("{")
100
+ end = text.rfind("}")
101
+ if start >= 0 and end > start:
102
+ try:
103
+ return json.loads(text[start:end + 1])
104
+ except Exception:
105
+ return None
106
+ return None
107
+
108
+
109
+ def offered_ids(row):
110
+ user = next(m for m in row["messages"] if m["role"] == "user")
111
+ payload = json.loads(user["content"])
112
+ return {c["nodeId"] for c in payload.get("candidates", [])}
113
+
114
+
115
+ def reference_cited(row):
116
+ return set(json.loads(row["messages"][-1]["content"]).get("citedNodeIds") or [])
117
+
118
+
119
+ def prompt_messages(row):
120
+ return [m for m in row["messages"] if m["role"] in ("system", "user")]
121
+
122
+
123
+ def cross_field_ok(plan, offered):
124
+ steps = plan.get("steps") or []
125
+ cited = plan.get("citedNodeIds") or []
126
+ decision = plan.get("decision")
127
+ abstain_reason = plan.get("abstainReason", None)
128
+ plan_cand_ids = [c.get("nodeId") for c in (plan.get("candidates") or [])]
129
+ plan_cand_set = set(plan_cand_ids)
130
+ if any(cid not in offered for cid in plan_cand_ids):
131
+ return False
132
+ if any(s.get("nodeId") not in plan_cand_set for s in steps):
133
+ return False
134
+ if any(cid not in plan_cand_set for cid in cited):
135
+ return False
136
+ cite_steps = {s.get("nodeId") for s in steps if s.get("action") == "CITE"}
137
+ if cite_steps != set(cited):
138
+ return False
139
+ if decision == "ABSTAIN":
140
+ return len(cited) == 0 and bool(abstain_reason)
141
+ if decision == "NAVIGATE":
142
+ return len(cited) >= 1 and abstain_reason is None
143
+ return False
144
+
145
+
146
+ def load_model(path, four_bit=False):
147
+ if four_bit:
148
+ from transformers import BitsAndBytesConfig
149
+ model = AutoModelForCausalLM.from_pretrained(
150
+ path,
151
+ quantization_config=BitsAndBytesConfig(
152
+ load_in_4bit=True,
153
+ bnb_4bit_quant_type="nf4",
154
+ bnb_4bit_compute_dtype=torch.bfloat16,
155
+ ),
156
+ device_map="auto",
157
+ )
158
+ else:
159
+ model = AutoModelForCausalLM.from_pretrained(
160
+ path, dtype=torch.float16, device_map="auto"
161
+ )
162
+ return model.eval()
163
+
164
+
165
+ def run_eval(model, tok, navigate, adversarial, schema, tag):
166
+ validator = validator_for(schema)(schema)
167
+ plan_total = len(navigate) + len(adversarial)
168
+ plan_valid = 0
169
+ hallucinated = 0
170
+ per_row = []
171
+
172
+ def generate_plan(row):
173
+ prompt = tok.apply_chat_template(
174
+ prompt_messages(row), tokenize=False, add_generation_prompt=True
175
+ )
176
+ inputs = tok(prompt, return_tensors="pt").to(model.device)
177
+ with torch.no_grad():
178
+ out = model.generate(**inputs, max_new_tokens=1024, do_sample=False,
179
+ pad_token_id=tok.eos_token_id)
180
+ full = tok.batch_decode(out, skip_special_tokens=True)[0]
181
+ prompt_len = len(tok.batch_decode(inputs["input_ids"], skip_special_tokens=True)[0])
182
+ return full[prompt_len:]
183
+
184
+ def score(row, split, i, n):
185
+ nonlocal plan_valid, hallucinated
186
+ offered = offered_ids(row)
187
+ t0 = time.time()
188
+ raw = generate_plan(row)
189
+ plan = extract_json(raw)
190
+ valid = False
191
+ if isinstance(plan, dict):
192
+ try:
193
+ validator.validate(plan)
194
+ valid = cross_field_ok(plan, offered)
195
+ except Exception:
196
+ valid = False
197
+ if valid:
198
+ plan_valid += 1
199
+ if isinstance(plan, dict):
200
+ hallucinated += sum(1 for c in (plan.get("citedNodeIds") or []) if c not in offered)
201
+ rec = {
202
+ "split": split, "i": i, "valid": bool(valid),
203
+ "decision": plan.get("decision") if isinstance(plan, dict) else None,
204
+ "citedNodeIds": plan.get("citedNodeIds") if isinstance(plan, dict) else None,
205
+ "secs": round(time.time() - t0, 1),
206
+ "raw": raw[:2000],
207
+ }
208
+ per_row.append(rec)
209
+ print(f"[{tag}] {split} {i}/{n} valid={valid} decision={rec['decision']} ({rec['secs']}s)")
210
+ return plan if isinstance(plan, dict) else None, valid
211
+
212
+ grounding_total = len(navigate)
213
+ grounding_correct = 0
214
+ for i, row in enumerate(navigate, 1):
215
+ plan, valid = score(row, "navigate", i, grounding_total)
216
+ if valid and plan and plan.get("decision") == "NAVIGATE" \
217
+ and set(plan.get("citedNodeIds") or []) == reference_cited(row):
218
+ grounding_correct += 1
219
+
220
+ abstain_total = len(adversarial)
221
+ abstain_correct = 0
222
+ for i, row in enumerate(adversarial, 1):
223
+ plan, valid = score(row, "adversarial", i, abstain_total)
224
+ if valid and plan and plan.get("decision") == "ABSTAIN":
225
+ abstain_correct += 1
226
+
227
+ print(f"[{tag}] MEASURED plan-valid {plan_valid}/{plan_total} | "
228
+ f"routing {grounding_correct}/{grounding_total} | "
229
+ f"abstain {abstain_correct}/{abstain_total} | "
230
+ f"hallucinated-citations {hallucinated}")
231
+ return {
232
+ "label": "MEASURED",
233
+ "method": f"merged checkpoint, {'nf4' if 'nf4' in tag else 'fp16'}, "
234
+ "scoring ported from eval_khipu.py, temperature 0",
235
+ "host": platform.node(),
236
+ "evaluatedAt": datetime.now(timezone.utc).isoformat(),
237
+ "planTotal": plan_total, "planValid": plan_valid,
238
+ "groundingTotal": grounding_total, "groundingCorrect": grounding_correct,
239
+ "abstainTotal": abstain_total, "abstainCorrect": abstain_correct,
240
+ "hallucinatedCitationCount": hallucinated,
241
+ "held_out_in_gradients": False,
242
+ "temperature": 0,
243
+ "rows": per_row,
244
+ }
245
+
246
+
247
+ def main():
248
+ ap = argparse.ArgumentParser()
249
+ ap.add_argument("--model", required=True, help="path to merged KHIPU-R2 dir")
250
+ ap.add_argument("--compare-4bit", action="store_true")
251
+ ap.add_argument("--curriculum-dir", default="khipu-curriculum")
252
+ ap.add_argument("--out", type=Path, default=None)
253
+ args = ap.parse_args()
254
+
255
+ local = fetch_curriculum(args.curriculum_dir)
256
+ navigate = load_jsonl(local["eval.jsonl"])
257
+ adversarial = load_jsonl(local["adversarial.jsonl"])
258
+ schema = json.loads(local["khipu.schema.json"].read_text(encoding="utf-8"))
259
+
260
+ tok = AutoTokenizer.from_pretrained(args.model)
261
+ results = {"fp16": run_eval(load_model(args.model), tok, navigate, adversarial, schema, "fp16")}
262
+
263
+ if args.compare_4bit:
264
+ gc.collect()
265
+ torch.cuda.empty_cache()
266
+ results["nf4"] = run_eval(load_model(args.model, four_bit=True), tok,
267
+ navigate, adversarial, schema, "nf4")
268
+ for a, b in zip(results["fp16"]["rows"], results["nf4"]["rows"]):
269
+ if a["valid"] != b["valid"] or a["decision"] != b["decision"]:
270
+ print(f"DIVERGED {a['split']} {a['i']}: fp16={a['decision']} nf4={b['decision']}")
271
+
272
+ if args.out:
273
+ args.out.parent.mkdir(parents=True, exist_ok=True)
274
+ args.out.write_text(json.dumps(results, indent=2), encoding="utf-8")
275
+ print(f"wrote {args.out}")
276
+
277
+
278
+ if __name__ == "__main__":
279
+ main()