CinderD commited on
Commit
b37dd4f
·
verified ·
1 Parent(s): 9c7ab6a

Fix evaluation harness and normalize rubrics

Browse files

Normalize rubric encodings for wildtrace-0195, wildtrace-0371, and wildtrace-0419; support HF JSONL ground-truth fields; create output directories; enforce complete judge panels; report Scored and All481 aggregation; refresh documentation and checksums.

CHECKSUMS.sha256 CHANGED
@@ -1,5 +1,5 @@
1
  0bd74a4ae3fd93117c71de4eff9514e14c8d9c7c936f17ed62298b8a2bff4c3c LICENSE
2
- caa35af7fe9087012bb7e9548cf51ff2434168a982456ac725957d381c8fa1bc README.md
3
  69077a8632a9b760d542f51fd979ac8f48c7f4785a8da28028b554eee78c26fa corpus/source-0001.txt
4
  89053a97930794a97cf842bc72042475d20c776dae82d734ffe97cb5e11ef967 corpus/source-0002.txt
5
  1ca60b578d990db5324489e767603f5d71021480c24cb91750125f2ea6a2a49c corpus/source-0003.txt
@@ -217,16 +217,16 @@ d6acba7c1463a690bd850eeeb04359469d29e7e965f2a9f2f7b918ff9d11f4fe corpus/source-
217
  5cd62c628bbaae5365a28c584d1fc0626c8288e6d7b3fc02e0e724106ee57f89 croissant.json
218
  89f19eabc8dd8e84f87454974d953b6f0e45fe16b4d89b52f7901994a28a8a2a data/wildtrace_strict481.questions_only.json
219
  2218cff5b98c62bf97c9d6facc16a0d715c6c9d231095b3da69d1bfbe63ee9f3 data/wildtrace_strict481.questions_only.jsonl
220
- d9794618dd1762b37d6873a28bfe45ba230d8c3749141c6e086c3bfe515a222f data/wildtrace_strict481.with_answers.json
221
- bb84003a2e0144f6f2e9d29533f2370347a698cc9c7877dcc46e4a3e57ab5f24 data/wildtrace_strict481.with_answers.jsonl
222
- 0f37435e7724723cfa15e8735ffc1ea9dddedbf30d3ab3034c043cfaf09fa9bf eval/config.json
223
- fb0b7ba21a0990f1f4c23e2cc7fa09d89e6dc3f52b0be9a166ccdbabe6e30ba1 eval/run_eval.py
224
- ac138baa999b926d632a9d05b53770b3c0fb6faad232e774a9a30ff24f770a9d eval/run_judge.py
225
  2a4dbda88b6436e80c2e324196edb4e662306ad2898ea42deb90f1673422bb85 metadata/corpora_manifest.csv
226
  0c1c65118131cc01a7c41c300e8792293074f8b914a8e23a4cec2bd0d00756e4 metadata/corpora_manifest.json
227
  3a5df0f909776ea657bc9bd9951d633fde8a37ee8ee33bb38a7d14af40240909 metadata/dataset_stats.json
228
  426dd91bf6e37246af75b071b3ae0b498e81632c1edb62a831ff322889484c0e metadata/release_manifest.json
229
  b1f38eb3ffbfa4d37d921f1a2f65ac26dd4dad6b81a14c0b7d19bf9a4a3fde03 metadata/schema.json
230
- c942d195d66190a88da6ccefdd4aa355dca230de3c84b06c9d98d182edd34b65 methodology/EVAL_PROTOCOL.md
231
  9216f159b8475a29f5ef7f797e97c511cc6185ee80985ad863df42e1cb80c214 upload_to_hf.py
232
  bbc809f06ee9dab93d9b98e83919a3456b7e3619a991ae75e4f5fefddeabbc6d upload_to_hf.sh
 
1
  0bd74a4ae3fd93117c71de4eff9514e14c8d9c7c936f17ed62298b8a2bff4c3c LICENSE
2
+ 187e3481d181a7eb8ecbed5b90408022a3e627ab212c0ad1b9632113a006fb60 README.md
3
  69077a8632a9b760d542f51fd979ac8f48c7f4785a8da28028b554eee78c26fa corpus/source-0001.txt
4
  89053a97930794a97cf842bc72042475d20c776dae82d734ffe97cb5e11ef967 corpus/source-0002.txt
5
  1ca60b578d990db5324489e767603f5d71021480c24cb91750125f2ea6a2a49c corpus/source-0003.txt
 
217
  5cd62c628bbaae5365a28c584d1fc0626c8288e6d7b3fc02e0e724106ee57f89 croissant.json
218
  89f19eabc8dd8e84f87454974d953b6f0e45fe16b4d89b52f7901994a28a8a2a data/wildtrace_strict481.questions_only.json
219
  2218cff5b98c62bf97c9d6facc16a0d715c6c9d231095b3da69d1bfbe63ee9f3 data/wildtrace_strict481.questions_only.jsonl
220
+ e50e58e89ec79c88e7dde387a633b78a6dff6a6abfef0c5f94110eec939c527d data/wildtrace_strict481.with_answers.json
221
+ 42feb334cd9b463e1bdf8e7d39c79aa40e13ae73797b580d6e6156aa09fb985b data/wildtrace_strict481.with_answers.jsonl
222
+ 7f87bca51db65b08e5f45441977ef721dae68017ee44f543477cf8d4299abf7b eval/config.json
223
+ 614f15526babfb8fbf027ad805b763a87101fea310627c093bb1afbffd12a810 eval/run_eval.py
224
+ 83b08805933a66d9a7ea1927eaddeb813cff6beedc957806811eabbe10cac0cd eval/run_judge.py
225
  2a4dbda88b6436e80c2e324196edb4e662306ad2898ea42deb90f1673422bb85 metadata/corpora_manifest.csv
226
  0c1c65118131cc01a7c41c300e8792293074f8b914a8e23a4cec2bd0d00756e4 metadata/corpora_manifest.json
227
  3a5df0f909776ea657bc9bd9951d633fde8a37ee8ee33bb38a7d14af40240909 metadata/dataset_stats.json
228
  426dd91bf6e37246af75b071b3ae0b498e81632c1edb62a831ff322889484c0e metadata/release_manifest.json
229
  b1f38eb3ffbfa4d37d921f1a2f65ac26dd4dad6b81a14c0b7d19bf9a4a3fde03 metadata/schema.json
230
+ 711b8d03de08a763159686ad4da9e393f92d4e87f6dd4f7f2fb87a282bcf387e methodology/EVAL_PROTOCOL.md
231
  9216f159b8475a29f5ef7f797e97c511cc6185ee80985ad863df42e1cb80c214 upload_to_hf.py
232
  bbc809f06ee9dab93d9b98e83919a3456b7e3619a991ae75e4f5fefddeabbc6d upload_to_hf.sh
README.md CHANGED
@@ -119,7 +119,7 @@ from datasets import load_dataset
119
 
120
  ds = load_dataset(
121
  "json",
122
- data_files="hf_release_wildtrace_strict481_20260621/data/wildtrace_strict481.with_answers.jsonl",
123
  split="train",
124
  )
125
  print(ds[0]["question_id"])
@@ -134,16 +134,37 @@ from datasets import load_dataset
134
  ds = load_dataset("CinderD/wildtrace", "with_answers", split="test")
135
  ```
136
 
137
- To evaluate a model, use `eval/run_eval.py` with `--corpus ../corpus`; the
138
- script constructs the evidence-withheld prompt from `question_text` and the full
139
- source document. Use `eval/run_judge.py` to score answers against the hidden
140
- rubric. See `methodology/EVAL_PROTOCOL.md` before reporting new results.
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
  ## Scoring Denominators
143
 
144
- When reporting model results, distinguish valid-response quality from
145
- coverage-sensitive all-task quality. The protocol document defines both views
146
- and the treatment of out-of-context or failed rows.
 
 
 
 
 
 
 
 
147
 
148
  ## Quality Assurance
149
 
@@ -179,12 +200,11 @@ terms before redistributing or adapting source texts.
179
  ## Citation
180
 
181
  ```bibtex
182
- @misc{wildtrace2026,
183
- title={WILDTRACE: Benchmarking Multi-Hop Reasoning over Natural Evidence Trails in Long Contexts},
184
- author={WildTrace authors},
185
  year={2026},
186
- howpublished={Hugging Face dataset},
187
- url={https://huggingface.co/datasets/CinderD/wildtrace},
188
- note={strict481 public release, freeze wildtrace_strict481_public_20260710}
189
  }
190
  ```
 
119
 
120
  ds = load_dataset(
121
  "json",
122
+ data_files="data/wildtrace_strict481.with_answers.jsonl",
123
  split="train",
124
  )
125
  print(ds[0]["question_id"])
 
134
  ds = load_dataset("CinderD/wildtrace", "with_answers", split="test")
135
  ```
136
 
137
+ To evaluate a model, clone the complete dataset repository, configure the model
138
+ and judge endpoints in `eval/config.json`, and run:
139
+
140
+ ```bash
141
+ cd eval
142
+ python run_eval.py --config config.json \
143
+ --data ../data/wildtrace_strict481.with_answers.json \
144
+ --corpus ../corpus --out ../results/mymodel.responses.json
145
+ python run_judge.py --config config.json \
146
+ --data ../data/wildtrace_strict481.with_answers.json \
147
+ --responses ../results/mymodel.responses.json \
148
+ --out ../results/mymodel.scores.json
149
+ ```
150
+
151
+ The scripts create the output directory automatically. Both the nested `.json`
152
+ and Hugging Face `.jsonl` representations are accepted. See
153
+ `methodology/EVAL_PROTOCOL.md` before reporting new results.
154
 
155
  ## Scoring Denominators
156
 
157
+ The score file reports both `scored_overall` (valid-response quality) and
158
+ `all_tasks_overall`/`overall` (coverage-sensitive All481 quality). Missing,
159
+ failed, and out-of-context model responses receive zero in All481. A judge API
160
+ or parse failure leaves `overall` null and exits nonzero instead of silently
161
+ averaging a partial judge panel; rerun the same command to resume.
162
+
163
+ ## Maintenance Notes
164
+
165
+ - 2026-08-13: normalized three legacy rubric encodings, added HF JSONL support,
166
+ automatic output-directory creation, complete-panel judging, and explicit
167
+ Scored/All481 aggregation. Refreshed release checksums.
168
 
169
  ## Quality Assurance
170
 
 
200
  ## Citation
201
 
202
  ```bibtex
203
+ @article{chen2026wildtrace,
204
+ title={WildTrace: Benchmarking Natural Evidence Trails in Long-Context Reasoning},
205
+ author={Chen, Zixin and Liu, Peng and Li, Haobo and Sheng, Rui and Tu, Jianhong and Deng, Xiaodong and Huang, Fei and Shum, Kashun and Liu, Dayiheng and Qu, Huamin},
206
  year={2026},
207
+ journal={arXiv preprint arXiv:2607.09328},
208
+ url={https://arxiv.org/abs/2607.09328}
 
209
  }
210
  ```
data/wildtrace_strict481.with_answers.json CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d9794618dd1762b37d6873a28bfe45ba230d8c3749141c6e086c3bfe515a222f
3
- size 6420902
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e50e58e89ec79c88e7dde387a633b78a6dff6a6abfef0c5f94110eec939c527d
3
+ size 6421202
data/wildtrace_strict481.with_answers.jsonl CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:bb84003a2e0144f6f2e9d29533f2370347a698cc9c7877dcc46e4a3e57ab5f24
3
- size 6254460
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:42feb334cd9b463e1bdf8e7d39c79aa40e13ae73797b580d6e6156aa09fb985b
3
+ size 6254535
eval/run_eval.py CHANGED
@@ -52,6 +52,27 @@ def is_cjk(text):
52
  return sum(1 for ch in text[:4000] if "一" <= ch <= "鿿") > 20
53
 
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  def post(url, key, payload, timeout):
56
  last = None
57
  for attempt in range(5):
@@ -104,19 +125,25 @@ def main():
104
  ap.add_argument("--out", required=True, help="output responses json")
105
  ap.add_argument("--workers", type=int, default=4)
106
  args = ap.parse_args()
107
- cfg = json.load(open(args.config))
 
 
108
  caps = load_caps(cfg)
109
  cap_key = cfg["model"] if cfg["model"] in caps else cfg.get("cap_key", "default")
110
 
111
- rows = ([json.loads(l) for l in open(args.data) if l.strip()]
112
- if args.data.endswith(".jsonl") else json.load(open(args.data)))
 
113
  rows = {r["question_id"]: r for r in rows}
114
 
115
  done = {}
116
  if os.path.exists(args.out):
117
- for r in json.load(open(args.out)):
 
 
118
  resp = r["model_response"]
119
- if resp and (not resp.startswith("[ERROR") or resp.startswith("[ERROR out_of_context_scope")):
 
120
  done[r["question_id"]] = r # terminal: keep; transient errors retry
121
  work = [qid for qid in rows if qid not in done]
122
  _docs, lock = {}, Lock()
@@ -130,7 +157,7 @@ def main():
130
  print(f"model={cfg['model']} cap_key={cap_key} | to do={len(work)} (done={len(done)})", flush=True)
131
 
132
  def run(qid):
133
- r = rows[qid]; gt = r.get("ground_truth", {})
134
  q = r.get("question_text") or gt.get("question_text")
135
  text = doc(r["corpus_file"])
136
  cap = caps[cap_key]["cjk" if is_cjk(text) else "en"]
@@ -140,7 +167,9 @@ def main():
140
  "doc_chars": len(text), "cap_chars": cap}, "oos"
141
  resp, err = call_model(EVAL_PROMPT.format(q=q, ctx=text[:cap]), cfg)
142
  if resp is None:
143
- return qid, None, f"FAIL {str(err)[:60]}" # transient -> not persisted, retries on resume
 
 
144
  return qid, {"question_id": qid, "paradigm": r.get("paradigm"),
145
  "model_response": resp, "doc_chars": len(text), "cap_chars": cap}, "ok"
146
 
@@ -151,7 +180,7 @@ def main():
151
  if row:
152
  with lock:
153
  done[qid] = row
154
- json.dump(list(done.values()), open(args.out, "w"), ensure_ascii=False, indent=2)
155
  if n % 20 == 0 or tag.startswith("FAIL"):
156
  print(f"[{n}/{len(work)}] {qid[:40]} -> {tag}", flush=True)
157
  print(f"DONE: {len(done)}/{len(rows)} -> {args.out}", flush=True)
 
52
  return sum(1 for ch in text[:4000] if "一" <= ch <= "鿿") > 20
53
 
54
 
55
+ def parse_ground_truth(value):
56
+ """Accept both nested JSON objects and HF JSONL's serialized JSON field."""
57
+ if isinstance(value, dict):
58
+ return value
59
+ if isinstance(value, str):
60
+ try:
61
+ parsed = json.loads(value)
62
+ return parsed if isinstance(parsed, dict) else {}
63
+ except json.JSONDecodeError:
64
+ return {}
65
+ return {}
66
+
67
+
68
+ def write_json(path, value):
69
+ """Write resumable manifests atomically so interruptions do not corrupt them."""
70
+ tmp = f"{path}.tmp"
71
+ with open(tmp, "w", encoding="utf-8") as f:
72
+ json.dump(value, f, ensure_ascii=False, indent=2)
73
+ os.replace(tmp, path)
74
+
75
+
76
  def post(url, key, payload, timeout):
77
  last = None
78
  for attempt in range(5):
 
125
  ap.add_argument("--out", required=True, help="output responses json")
126
  ap.add_argument("--workers", type=int, default=4)
127
  args = ap.parse_args()
128
+ os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)
129
+ with open(args.config, encoding="utf-8") as f:
130
+ cfg = json.load(f)
131
  caps = load_caps(cfg)
132
  cap_key = cfg["model"] if cfg["model"] in caps else cfg.get("cap_key", "default")
133
 
134
+ with open(args.data, encoding="utf-8") as f:
135
+ rows = ([json.loads(l) for l in f if l.strip()]
136
+ if args.data.endswith(".jsonl") else json.load(f))
137
  rows = {r["question_id"]: r for r in rows}
138
 
139
  done = {}
140
  if os.path.exists(args.out):
141
+ with open(args.out, encoding="utf-8") as f:
142
+ previous = json.load(f)
143
+ for r in previous:
144
  resp = r["model_response"]
145
+ if (r.get("question_id") in rows and resp and
146
+ (not resp.startswith("[ERROR") or resp.startswith("[ERROR out_of_context_scope"))):
147
  done[r["question_id"]] = r # terminal: keep; transient errors retry
148
  work = [qid for qid in rows if qid not in done]
149
  _docs, lock = {}, Lock()
 
157
  print(f"model={cfg['model']} cap_key={cap_key} | to do={len(work)} (done={len(done)})", flush=True)
158
 
159
  def run(qid):
160
+ r = rows[qid]; gt = parse_ground_truth(r.get("ground_truth", {}))
161
  q = r.get("question_text") or gt.get("question_text")
162
  text = doc(r["corpus_file"])
163
  cap = caps[cap_key]["cjk" if is_cjk(text) else "en"]
 
167
  "doc_chars": len(text), "cap_chars": cap}, "oos"
168
  resp, err = call_model(EVAL_PROMPT.format(q=q, ctx=text[:cap]), cfg)
169
  if resp is None:
170
+ return qid, {"question_id": qid, "paradigm": r.get("paradigm"),
171
+ "model_response": f"[ERROR inference_failed: {str(err)[:240]}]",
172
+ "doc_chars": len(text), "cap_chars": cap}, f"FAIL {str(err)[:60]}"
173
  return qid, {"question_id": qid, "paradigm": r.get("paradigm"),
174
  "model_response": resp, "doc_chars": len(text), "cap_chars": cap}, "ok"
175
 
 
180
  if row:
181
  with lock:
182
  done[qid] = row
183
+ write_json(args.out, list(done.values()))
184
  if n % 20 == 0 or tag.startswith("FAIL"):
185
  print(f"[{n}/{len(work)}] {qid[:40]} -> {tag}", flush=True)
186
  print(f"DONE: {len(done)}/{len(rows)} -> {args.out}", flush=True)
eval/run_judge.py CHANGED
@@ -1,39 +1,100 @@
1
  #!/usr/bin/env python3
2
- """WildTrace rubric judge harness (3-judge non-contestant panel, averaged).
3
 
4
- Scores a model's answers (from run_eval.py) against each task's rubric. Each answer is graded
5
- by THREE non-contestant judges and the three scores are AVERAGED (simple mean, no same-family
6
- exclusion). out_of_context_scope answers stay 0 (the model could not ingest the evidence).
7
-
8
- Panel used in the paper (deliberately models NOT on the leaderboard):
9
- Claude-Sonnet-4.6 · Qwen3.5 · Gemini-2.5-Flash
10
- Supply your own judge endpoints in config.json -> "judges". OpenAI-compatible chat endpoints are
11
- the default; gateways that expose Gemini through native `contents`/`candidates` payloads can set
12
- `"api_type": "gemini_native"` on that judge. Using a single judge is supported (list one) but the
13
- paper headline is the 3-judge average.
14
-
15
- Output: results/<model>.scores.json
16
- { "per_judge": {judge: {qid: score_0_1}}, "average": {qid: mean_score}, "overall": pct }
17
 
18
  Usage:
19
  export API_KEY=sk-...
20
- python run_judge.py --config config.json --data ../data/wildtrace_strict481.with_answers.json \
21
- --responses ../results/mymodel.responses.json --out ../results/mymodel.scores.json
 
 
22
  """
23
- import argparse, ast, json, os, re, time, urllib.request, urllib.error
 
 
 
 
 
 
 
24
  from concurrent.futures import ThreadPoolExecutor, as_completed
25
  from threading import Lock
26
 
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  def post(url, key, payload, timeout=180):
29
  for attempt in range(4):
30
  if attempt:
31
  time.sleep(3 * attempt)
32
  try:
33
- req = urllib.request.Request(url, data=json.dumps(payload).encode(),
34
- headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"})
35
- with urllib.request.urlopen(req, timeout=timeout) as r:
36
- return json.loads(r.read())
 
 
 
 
 
 
37
  except Exception:
38
  pass
39
  return None
@@ -62,12 +123,16 @@ def build_payload(judge_cfg, prompt):
62
 
63
  def response_content(data):
64
  content = (data.get("choices", [{}])[0].get("message", {}) or {}).get("content", "")
65
- if not content and isinstance(data.get("content"), list): # Anthropic-native content blocks
66
- content = "".join(b.get("text", "") for b in data["content"] if b.get("type") == "text")
67
- if not content and isinstance(data.get("candidates"), list): # Gemini-native candidates
 
 
 
 
68
  parts = []
69
- for cand in data["candidates"]:
70
- for part in ((cand.get("content") or {}).get("parts") or []):
71
  if part.get("text"):
72
  parts.append(part["text"])
73
  content = "".join(parts)
@@ -75,103 +140,220 @@ def response_content(data):
75
 
76
 
77
  def build_judge_prompt(question, rubric, response):
78
- if isinstance(rubric, str):
79
- try: rubric = ast.literal_eval(rubric)
80
- except Exception: rubric = []
81
- if not isinstance(rubric, list): rubric = []
82
- rt = "".join(f'P{i+1} ({p.get("points", 0)}pts): {p.get("correct_criterion", "")[:260]}\n'
83
- for i, p in enumerate(rubric) if isinstance(p, dict))
84
- return ("STRICT grader. Only award points for SPECIFIC details present.\n"
85
- f"QUESTION: {question[:600]}\nRUBRIC:\n{rt}\nRESPONSE:\n{response[:5000]}\n"
86
- 'Reply JSON: {"points_awarded":[<pts>],"total":<sum>}')
 
 
 
87
 
88
 
89
  def parse_total(content):
90
  if not content:
91
  return None
92
- t = re.sub(r"^```(?:json)?\s*", "", content.strip()); t = re.sub(r"\s*```$", "", t)
93
- m = re.search(r'\{.*"total".*\}', t, re.DOTALL)
94
- if not m:
 
95
  return None
96
  try:
97
- return float(json.loads(m.group())["total"])
98
- except Exception:
99
  return None
100
 
101
 
102
  def judge_one(judge_cfg, key, question, rubric, response):
103
- """One judge's score in [0,1], or None on failure. total is a 0-100 sum -> /100, capped at 1."""
104
- prompt = build_judge_prompt(question, rubric, response)
105
  data = post(judge_cfg["base_url"], key, build_payload(judge_cfg, prompt))
106
  if not data:
107
  return None
108
- content = response_content(data)
109
- tot = parse_total(content)
110
- return None if tot is None else min(tot / 100.0, 1.0)
111
 
112
 
113
  def main():
114
- ap = argparse.ArgumentParser()
115
- ap.add_argument("--config", default="config.json")
116
- ap.add_argument("--data", required=True)
117
- ap.add_argument("--responses", required=True)
118
- ap.add_argument("--out", required=True)
119
- ap.add_argument("--workers", type=int, default=8)
120
- args = ap.parse_args()
121
- cfg = json.load(open(args.config))
122
- judges = cfg["judges"] # list of {name, base_url, model, api_key_env?, max_tokens?}
123
- rows = ([json.loads(l) for l in open(args.data) if l.strip()]
124
- if args.data.endswith(".jsonl") else json.load(open(args.data)))
125
- rows = {r["question_id"]: r for r in rows}
126
- responses = {r["question_id"]: r for r in json.load(open(args.responses))}
127
-
128
- out = json.load(open(args.out)) if os.path.exists(args.out) else {"per_judge": {}, "average": {}, "overall": None}
129
- per = out["per_judge"]
130
- for j in judges:
131
- per.setdefault(j["name"], {})
132
-
133
- # work: (judge, qid) for non-oos answers not yet judged; oos -> score 0 directly
134
- oos = {qid for qid, r in responses.items() if str(r["model_response"]).startswith("[ERROR out_of_context_scope")}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  work = []
136
- for j in judges:
137
- for qid, r in responses.items():
138
- if qid in oos or qid not in rows:
139
- continue
140
- if str(r["model_response"]).startswith("[ERROR"): # transient eval failure: skip, not judged
141
- continue
142
- if per[j["name"]].get(qid) is None:
143
- work.append((j, qid))
144
- print(f"judges={[j['name'] for j in judges]} | oos(score0)={len(oos)} | to judge={len(work)}", flush=True)
145
- lock = Lock(); n = [0]
 
 
146
 
147
  def run(item):
148
- j, qid = item
149
- r = rows[qid]; gt = r.get("ground_truth", {})
150
- q = r.get("question_text") or gt.get("question_text")
151
- key = os.environ[j.get("api_key_env", cfg.get("api_key_env", "API_KEY"))]
152
- sc = judge_one(j, key, q, gt.get("scoring_rubric") or [], responses[qid]["model_response"])
 
 
 
 
 
 
 
153
  with lock:
154
- per[j["name"]][qid] = sc; n[0] += 1
155
- if n[0] % 100 == 0:
156
- json.dump(out, open(args.out, "w"), ensure_ascii=False, indent=2)
157
- print(f"{n[0]}/{len(work)}", flush=True)
158
-
159
- with ThreadPoolExecutor(max_workers=args.workers) as ex:
160
- list(as_completed([ex.submit(run, it) for it in work]))
161
-
162
- # aggregate: per task, average the available judge scores; oos -> 0
163
- avg = {}
164
- all_qids = set(oos) | {qid for jn in per for qid in per[jn]}
165
- for qid in all_qids:
166
- if qid in oos:
167
- avg[qid] = 0.0; continue
168
- vals = [per[jn][qid] for jn in per if per[jn].get(qid) is not None]
169
- if vals:
170
- avg[qid] = sum(vals) / len(vals)
171
- out["average"] = avg
172
- out["overall"] = round(100 * sum(avg.values()) / len(avg), 2) if avg else None
173
- json.dump(out, open(args.out, "w"), ensure_ascii=False, indent=2)
174
- print(f"DONE: overall={out['overall']} over n={len(avg)} -> {args.out}", flush=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
 
177
  if __name__ == "__main__":
 
1
  #!/usr/bin/env python3
2
+ """WildTrace rubric-judge harness.
3
 
4
+ Score answers produced by run_eval.py with one or more non-contestant judges.
5
+ The paper protocol uses three judges and averages their normalized rubric scores.
6
+ Out-of-context, failed, and missing model responses receive zero in the AllN view.
7
+ Judge API/parse failures never get silently averaged away: rerun the command to
8
+ resume them before an AllN score is emitted.
 
 
 
 
 
 
 
 
9
 
10
  Usage:
11
  export API_KEY=sk-...
12
+ python run_judge.py --config config.json \
13
+ --data ../data/wildtrace_strict481.with_answers.json \
14
+ --responses ../results/mymodel.responses.json \
15
+ --out ../results/mymodel.scores.json
16
  """
17
+
18
+ import argparse
19
+ import ast
20
+ import json
21
+ import os
22
+ import re
23
+ import time
24
+ import urllib.request
25
  from concurrent.futures import ThreadPoolExecutor, as_completed
26
  from threading import Lock
27
 
28
 
29
+ def parse_jsonish(value):
30
+ """Decode fields serialized by the Hugging Face JSONL representation."""
31
+ if not isinstance(value, str):
32
+ return value
33
+ try:
34
+ return json.loads(value)
35
+ except json.JSONDecodeError:
36
+ try:
37
+ return ast.literal_eval(value)
38
+ except (SyntaxError, ValueError):
39
+ return None
40
+
41
+
42
+ def parse_ground_truth(value):
43
+ value = parse_jsonish(value)
44
+ return value if isinstance(value, dict) else {}
45
+
46
+
47
+ def normalize_rubric(value):
48
+ """Return (points, criterion) pairs for canonical and legacy schemas."""
49
+ value = parse_jsonish(value)
50
+ if not isinstance(value, list) or not value:
51
+ raise ValueError("rubric must be a non-empty list")
52
+
53
+ normalized = []
54
+ for item in value:
55
+ if not isinstance(item, dict):
56
+ raise ValueError("every rubric criterion must be an object")
57
+ try:
58
+ points = float(item.get("points", 0))
59
+ except (TypeError, ValueError) as exc:
60
+ raise ValueError("rubric points must be numeric") from exc
61
+ if points <= 0:
62
+ raise ValueError("rubric points must be positive")
63
+
64
+ criterion = item.get("correct_criterion")
65
+ if not criterion:
66
+ label = str(item.get("criterion") or "").strip()
67
+ evidence = str(item.get("evidence") or "").strip()
68
+ criterion = ": ".join(part for part in (label, evidence) if part)
69
+ if not str(criterion).strip():
70
+ raise ValueError("rubric criterion text is empty")
71
+ normalized.append((points, str(criterion).strip()))
72
+ return normalized
73
+
74
+
75
+ def write_json(path, value):
76
+ """Atomically save resumable score state."""
77
+ tmp = f"{path}.tmp"
78
+ with open(tmp, "w", encoding="utf-8") as f:
79
+ json.dump(value, f, ensure_ascii=False, indent=2)
80
+ os.replace(tmp, path)
81
+
82
+
83
  def post(url, key, payload, timeout=180):
84
  for attempt in range(4):
85
  if attempt:
86
  time.sleep(3 * attempt)
87
  try:
88
+ request = urllib.request.Request(
89
+ url,
90
+ data=json.dumps(payload).encode(),
91
+ headers={
92
+ "Authorization": f"Bearer {key}",
93
+ "Content-Type": "application/json",
94
+ },
95
+ )
96
+ with urllib.request.urlopen(request, timeout=timeout) as response:
97
+ return json.loads(response.read())
98
  except Exception:
99
  pass
100
  return None
 
123
 
124
  def response_content(data):
125
  content = (data.get("choices", [{}])[0].get("message", {}) or {}).get("content", "")
126
+ if not content and isinstance(data.get("content"), list):
127
+ content = "".join(
128
+ block.get("text", "")
129
+ for block in data["content"]
130
+ if block.get("type") == "text"
131
+ )
132
+ if not content and isinstance(data.get("candidates"), list):
133
  parts = []
134
+ for candidate in data["candidates"]:
135
+ for part in ((candidate.get("content") or {}).get("parts") or []):
136
  if part.get("text"):
137
  parts.append(part["text"])
138
  content = "".join(parts)
 
140
 
141
 
142
  def build_judge_prompt(question, rubric, response):
143
+ normalized = normalize_rubric(rubric)
144
+ rubric_text = "".join(
145
+ f"P{i + 1} ({points:g}pts): {criterion[:260]}\n"
146
+ for i, (points, criterion) in enumerate(normalized)
147
+ )
148
+ prompt = (
149
+ "STRICT grader. Only award points for SPECIFIC details present.\n"
150
+ f"QUESTION: {question[:600]}\nRUBRIC:\n{rubric_text}\n"
151
+ f"RESPONSE:\n{response[:5000]}\n"
152
+ 'Reply JSON: {"points_awarded":[<pts>],"total":<sum>}'
153
+ )
154
+ return prompt, sum(points for points, _ in normalized)
155
 
156
 
157
  def parse_total(content):
158
  if not content:
159
  return None
160
+ text = re.sub(r"^```(?:json)?\s*", "", content.strip())
161
+ text = re.sub(r"\s*```$", "", text)
162
+ match = re.search(r'\{.*"total".*\}', text, re.DOTALL)
163
+ if not match:
164
  return None
165
  try:
166
+ return float(json.loads(match.group())["total"])
167
+ except (KeyError, TypeError, ValueError, json.JSONDecodeError):
168
  return None
169
 
170
 
171
  def judge_one(judge_cfg, key, question, rubric, response):
172
+ """Return one normalized score in [0,1], or None on API/parse failure."""
173
+ prompt, max_points = build_judge_prompt(question, rubric, response)
174
  data = post(judge_cfg["base_url"], key, build_payload(judge_cfg, prompt))
175
  if not data:
176
  return None
177
+ total = parse_total(response_content(data))
178
+ return None if total is None else max(0.0, min(total / max_points, 1.0))
 
179
 
180
 
181
  def main():
182
+ parser = argparse.ArgumentParser()
183
+ parser.add_argument("--config", default="config.json")
184
+ parser.add_argument("--data", required=True)
185
+ parser.add_argument("--responses", required=True)
186
+ parser.add_argument("--out", required=True)
187
+ parser.add_argument("--workers", type=int, default=8)
188
+ args = parser.parse_args()
189
+
190
+ os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)
191
+ with open(args.config, encoding="utf-8") as f:
192
+ cfg = json.load(f)
193
+ judges = cfg["judges"]
194
+ if not judges or len({judge["name"] for judge in judges}) != len(judges):
195
+ raise ValueError("config must contain at least one judge with a unique name")
196
+
197
+ with open(args.data, encoding="utf-8") as f:
198
+ data_rows = (
199
+ [json.loads(line) for line in f if line.strip()]
200
+ if args.data.endswith(".jsonl")
201
+ else json.load(f)
202
+ )
203
+ rows = {row["question_id"]: row for row in data_rows}
204
+ if len(rows) != len(data_rows):
205
+ raise ValueError("dataset contains duplicate question_id values")
206
+
207
+ with open(args.responses, encoding="utf-8") as f:
208
+ response_rows = json.load(f)
209
+ responses = {row["question_id"]: row for row in response_rows}
210
+ if len(responses) != len(response_rows):
211
+ raise ValueError("response manifest contains duplicate question_id values")
212
+
213
+ if os.path.exists(args.out):
214
+ with open(args.out, encoding="utf-8") as f:
215
+ out = json.load(f)
216
+ else:
217
+ out = {"per_judge": {}, "average": {}, "overall": None}
218
+ per_judge = out.setdefault("per_judge", {})
219
+ for judge in judges:
220
+ per_judge.setdefault(judge["name"], {})
221
+
222
+ missing = {qid for qid in rows if qid not in responses}
223
+ oos = {
224
+ qid
225
+ for qid, row in responses.items()
226
+ if qid in rows
227
+ and str(row.get("model_response", "")).startswith("[ERROR out_of_context_scope")
228
+ }
229
+ failed = {
230
+ qid
231
+ for qid, row in responses.items()
232
+ if qid in rows
233
+ and (
234
+ not str(row.get("model_response", "")).strip()
235
+ or str(row.get("model_response", "")).startswith("[ERROR")
236
+ )
237
+ and qid not in oos
238
+ }
239
+ valid = set(rows) - missing - oos - failed
240
+
241
+ # Validate every judge input before spending API calls.
242
+ ground_truth = {}
243
+ for qid in sorted(valid):
244
+ gt = parse_ground_truth(rows[qid].get("ground_truth", {}))
245
+ if not (rows[qid].get("question_text") or gt.get("question_text")):
246
+ raise ValueError(f"{qid}: missing question text")
247
+ try:
248
+ normalize_rubric(gt.get("scoring_rubric"))
249
+ except ValueError as exc:
250
+ raise ValueError(f"{qid}: {exc}") from exc
251
+ ground_truth[qid] = gt
252
+
253
  work = []
254
+ for judge in judges:
255
+ for qid in sorted(valid):
256
+ if per_judge[judge["name"]].get(qid) is None:
257
+ work.append((judge, qid))
258
+ print(
259
+ f"judges={[judge['name'] for judge in judges]} | valid={len(valid)} | "
260
+ f"zero_fill={len(missing | oos | failed)} | to_judge={len(work)}",
261
+ flush=True,
262
+ )
263
+
264
+ lock = Lock()
265
+ completed = [0]
266
 
267
  def run(item):
268
+ judge, qid = item
269
+ row = rows[qid]
270
+ gt = ground_truth[qid]
271
+ question = row.get("question_text") or gt.get("question_text")
272
+ env_name = judge.get("api_key_env", cfg.get("api_key_env", "API_KEY"))
273
+ score = judge_one(
274
+ judge,
275
+ os.environ[env_name],
276
+ question,
277
+ gt["scoring_rubric"],
278
+ responses[qid]["model_response"],
279
+ )
280
  with lock:
281
+ per_judge[judge["name"]][qid] = score
282
+ completed[0] += 1
283
+ if completed[0] % 100 == 0:
284
+ write_json(args.out, out)
285
+ print(f"{completed[0]}/{len(work)}", flush=True)
286
+
287
+ with ThreadPoolExecutor(max_workers=args.workers) as executor:
288
+ futures = [executor.submit(run, item) for item in work]
289
+ try:
290
+ for future in as_completed(futures):
291
+ future.result()
292
+ finally:
293
+ with lock:
294
+ write_json(args.out, out)
295
+
296
+ # Require the full configured panel for every valid response. A judge failure is not a
297
+ # contestant failure and must not be converted into zero or a smaller-panel average.
298
+ judge_names = [judge["name"] for judge in judges]
299
+ scored = {}
300
+ incomplete = {}
301
+ for qid in sorted(valid):
302
+ absent = [name for name in judge_names if per_judge[name].get(qid) is None]
303
+ if absent:
304
+ incomplete[qid] = absent
305
+ else:
306
+ scored[qid] = sum(float(per_judge[name][qid]) for name in judge_names) / len(judge_names)
307
+
308
+ zero_filled = missing | oos | failed
309
+ average = {qid: 0.0 for qid in sorted(zero_filled)}
310
+ average.update(scored)
311
+ scored_overall = round(100 * sum(scored.values()) / len(scored), 2) if scored else None
312
+ all_tasks_overall = (
313
+ round(100 * sum(average.values()) / len(rows), 2)
314
+ if rows and not incomplete
315
+ else None
316
+ )
317
+ out.update(
318
+ {
319
+ "average": average,
320
+ "scored_overall": scored_overall,
321
+ "scored_n": len(scored),
322
+ "valid_n": len(scored),
323
+ "all_tasks_overall": all_tasks_overall,
324
+ "all_tasks_n": len(rows),
325
+ "overall": all_tasks_overall,
326
+ "overall_definition": (
327
+ f"All{len(rows)}: missing, failed, and out-of-context responses are zero"
328
+ ),
329
+ "scoring_complete": not incomplete,
330
+ "response_manifest_complete": not missing,
331
+ "coverage": {
332
+ "responses_present": len(set(rows) & set(responses)),
333
+ "valid_responses": len(valid),
334
+ "out_of_context": len(oos),
335
+ "failed_responses": len(failed),
336
+ "missing_responses": len(missing),
337
+ "fully_judged": len(scored),
338
+ "incomplete_judging": len(incomplete),
339
+ },
340
+ "incomplete_judging": incomplete,
341
+ }
342
+ )
343
+ write_json(args.out, out)
344
+
345
+ if incomplete:
346
+ print(
347
+ f"INCOMPLETE: {len(incomplete)} valid responses lack one or more judge scores; "
348
+ f"resume the command -> {args.out}",
349
+ flush=True,
350
+ )
351
+ raise SystemExit(2)
352
+ print(
353
+ f"DONE: Scored={scored_overall} (n={len(scored)}), "
354
+ f"All{len(rows)}={all_tasks_overall} -> {args.out}",
355
+ flush=True,
356
+ )
357
 
358
 
359
  if __name__ == "__main__":
methodology/EVAL_PROTOCOL.md CHANGED
@@ -32,9 +32,7 @@ few-shot examples, no chain-of-thought instruction.
32
  ## 3. Context caps and out-of-context scoring
33
  Each model is evaluated **at its native context window**. The document is measured in
34
  **characters**; if `len(document) > cap` the task is **out_of_context_scope** and scored
35
- **0** — the document is NOT sent (a system that cannot ingest the evidence fails the task).
36
- This is the single most important convention: bottom-of-leaderboard models score low mainly
37
- because 40–50% of documents exceed their window.
38
 
39
  CJK detection: if the first 4000 chars contain >20 CJK ideographs (`一`–`鿿`), use the **cjk**
40
  cap, else the **en** cap (CJK packs more tokens per character).
@@ -67,8 +65,8 @@ judges show no measurable bias on this set). Panel used in the paper:
67
  | judge 2 | Qwen3.5 | `qwen3.5-plus` |
68
  | judge 3 | Gemini-2.5-Flash | `gemini-2.5-flash` |
69
 
70
- (Qwen3.5 is a *judge* here, hence it is not a graded contestant.) out_of_context_scope
71
- answers stay 0 and are not sent to judges.
72
 
73
  Exact judge prompt (per answer):
74
 
@@ -83,20 +81,23 @@ RESPONSE:
83
  Reply JSON: {"points_awarded":[<pts>],"total":<sum>}
84
  ```
85
 
86
- The rubric is the task's `ground_truth.scoring_rubric` (a list of `{points, correct_criterion}`).
87
- Judge settings: `temperature = 0.1`, `max_tokens = 16384`. Parse the `total` field
88
- (a 0–100 sum), score = `min(total / 100, 1.0)`. A task's final score = mean of the available
89
- judges' scores.
 
90
 
91
  ## 5. Aggregation
92
- - Per task, per model: mean of the 3 judges for valid scored responses; out-of-context rows
93
- are assigned 0 and are not sent to judges.
94
- - The paper reports two denominator views. `Scored` is valid-response quality: the mean over
95
- valid scored responses for that route, with `n` reporting the number of valid scored rows.
96
- `All481` is coverage-sensitive quality: all 481 attempted tasks are the denominator, and
97
- missing, failed, and out-of-context rows are zero-filled.
98
- - A matched-panel variant (tasks scored by all models) is reported only as a robustness check.
99
- It is not the headline denominator because it removes many long-context access failures.
 
 
100
 
101
  ## 6. Reproducing with the provided scripts
102
  ```bash
@@ -108,8 +109,13 @@ python run_eval.py --config config.json --data ../data/wildtrace_strict481.with
108
  # 2) edit config.json "judges" to your three judge endpoints
109
  python run_judge.py --config config.json --data ../data/wildtrace_strict481.with_answers.json \
110
  --responses ../results/mymodel.responses.json --out ../results/mymodel.scores.json
111
- # overall % is printed and stored at results/mymodel.scores.json -> "overall"
112
  ```
 
 
 
 
 
113
  LLM judges are non-deterministic, so a fresh run should be reported with the
114
  model route, endpoint date, context policy, decoding settings, and judge panel
115
  used for that run.
 
32
  ## 3. Context caps and out-of-context scoring
33
  Each model is evaluated **at its native context window**. The document is measured in
34
  **characters**; if `len(document) > cap` the task is **out_of_context_scope** and scored
35
+ **0** — the document is NOT sent. Treat this as route metadata, not as an item edit.
 
 
36
 
37
  CJK detection: if the first 4000 chars contain >20 CJK ideographs (`一`–`鿿`), use the **cjk**
38
  cap, else the **en** cap (CJK packs more tokens per character).
 
65
  | judge 2 | Qwen3.5 | `qwen3.5-plus` |
66
  | judge 3 | Gemini-2.5-Flash | `gemini-2.5-flash` |
67
 
68
+ (Qwen3.5 is a *judge* here, hence it is not a graded contestant.) Out-of-context
69
+ records stay at zero and are not sent to judges.
70
 
71
  Exact judge prompt (per answer):
72
 
 
81
  Reply JSON: {"points_awarded":[<pts>],"total":<sum>}
82
  ```
83
 
84
+ The rubric is the task's `ground_truth.scoring_rubric` (a list of
85
+ `{points, correct_criterion}`). Released rubric points sum to 100. Judge settings:
86
+ `temperature = 0.1`, `max_tokens = 16384`. Parse the `total` field and normalize by the
87
+ sum of rubric points. A task's final score is emitted only after all configured judges
88
+ succeed, then equals their simple mean.
89
 
90
  ## 5. Aggregation
91
+ - `Scored` (`scored_overall`, with `scored_n`) is valid-response quality: the mean
92
+ over valid responses successfully scored by the full configured judge panel.
93
+ - `All481` (`all_tasks_overall`, also exposed as `overall`) is coverage-sensitive:
94
+ all 481 tasks are the denominator, and missing, failed, and out-of-context model
95
+ responses are zero-filled.
96
+ - Judge API or parse failures are resumable infrastructure failures, not model
97
+ failures. The script writes partial state, leaves `overall` null, and exits with
98
+ status 2 until the complete configured panel succeeds.
99
+ - Do not mix scores produced under different route caps, prompts, retry policies,
100
+ judge panels, or aggregation policies.
101
 
102
  ## 6. Reproducing with the provided scripts
103
  ```bash
 
109
  # 2) edit config.json "judges" to your three judge endpoints
110
  python run_judge.py --config config.json --data ../data/wildtrace_strict481.with_answers.json \
111
  --responses ../results/mymodel.responses.json --out ../results/mymodel.scores.json
112
+ # Scored and All481 are printed; All481 is stored in "all_tasks_overall" and "overall"
113
  ```
114
+ Both released data representations are supported: the nested `.json` file and the
115
+ Hugging Face `.jsonl` file whose `ground_truth` field is serialized JSON. Output
116
+ directories are created automatically. Re-run either command to resume transient
117
+ model or judge failures.
118
+
119
  LLM judges are non-deterministic, so a fresh run should be reported with the
120
  model route, endpoint date, context policy, decoding settings, and judge panel
121
  used for that run.