Download code/evidence.py from lewtun/gitswarm-ablation-replication: direct link, hf CLI and curl.
- Browser
- Download file 17.2 kB
-
https://huggingface.co/datasets/lewtun/gitswarm-ablation-replication/resolve/main/code/evidence.py
- Command line
-
hf download hf://datasets/lewtun/gitswarm-ablation-replication/code/evidence.py
-
curl -L -o evidence.py https://huggingface.co/datasets/lewtun/gitswarm-ablation-replication/resolve/main/code/evidence.py
17.2 kB
| """C.3 Attribution: Retracted Evidence. | |
| Task (paper, verbatim protocol): an archive of source notes, derived evidence | |
| notes, and candidate conclusions. | |
| - A source note states a numerical claim ("specimen Iona has baseline | |
| resonance 22"). | |
| - A derived note names a specimen and metric, applies a signed numerical | |
| adjustment to one earlier claim, and reports the result. Its TRUE parent is | |
| the unique preceding note whose specimen, metric and value make the | |
| calculation correct. Decoy notes report nearby values; only one value makes | |
| each stated transformation correct. | |
| - A conclusion states that one candidate answers one question and names the | |
| claim required to support it. An artifact is valid only if its producer and | |
| every artifact in its ancestry remain valid. | |
| - One intermediate artifact is authored by a RETRACTED laboratory; multiple | |
| downstream branches attach to it, so all conclusions below it are invalid. | |
| - For each of P questions, exactly one of the C candidate conclusions has a | |
| fully clean lineage. | |
| Treatments: both give workers a persistent catalog + all earlier reads and | |
| submissions. attribution: catalog rows carry producer + immediate parent IDs. | |
| no_attribution: those fields are absent; lineage must be reconstructed from | |
| the numerical statements. The prompt does not name the treatment. | |
| Settings: P=4 questions, C=2 candidates, 4 sequential workers, 3 seeds; | |
| per-worker read budget k = ceil(|A|/4). Sweeps: lineage depth L, semantic | |
| ambiguity A, fan-out F, one factor at a time. | |
| Metric: fraction of unique archive artifacts read before the FIRST exact | |
| submission (a submission is exact when every question is answered with the | |
| unique clean-lineage candidate). | |
| """ | |
| import json | |
| import os | |
| import random | |
| import subprocess | |
| from agent import run_worker_episode | |
| def generate_archive(seed, P=4, C=2, L=4, A=1, F=2, n_decoys=8): | |
| """Build the archive. L: ancestry levels ending at a conclusion; | |
| A: plausible same-(specimen,metric) decoy parents per derivation step; | |
| F: downstream branches below the retracted artifact.""" | |
| rng = random.Random(seed) | |
| specimens = [f"specimen-{rng.randrange(100,999)}" for _ in range(6)] | |
| metrics = [f"metric-{chr(97+i)}" for i in range(4)] | |
| artifacts = {} # id -> artifact dict | |
| order = [] # generation order; a derived note's parent must precede it | |
| def new_id(kind, i): | |
| return f"{kind}{i:04d}_{rng.randrange(1000,9999)}" | |
| def _unique_adj(parent_val, sp, me): | |
| """Draw an adjustment whose result value does not coincide with any | |
| existing (sp, me) note, so the stated transform has exactly ONE | |
| valid source among earlier notes: the declared parent.""" | |
| taken = {a["value"] for a in artifacts.values() | |
| if a["type"] in ("source", "derived") | |
| and a["specimen"] == sp and a["metric"] == me} | |
| for _ in range(500): | |
| adj = rng.randrange(-9, 10) or 3 | |
| nv = parent_val + adj | |
| if nv not in taken and 0 <= nv < 300: | |
| return adj, nv | |
| raise RuntimeError("could not draw a unique adjustment") | |
| # --- retracted branch: one chain of length L ending at a conclusion, | |
| # the retracted node sits mid-chain with F downstream branches. | |
| retracted_idx = max(1, L // 2) | |
| spec0 = rng.choice(specimens) | |
| met0 = rng.choice(metrics) | |
| val = rng.randrange(5, 100) | |
| root_id = new_id("s", 0) | |
| artifacts[root_id] = {"type": "source", "specimen": spec0, "metric": met0, | |
| "value": val, "producer": "lab_alpha", | |
| "parent": None, "retracted": False, | |
| "text": f"Source note: {spec0} has baseline {met0} " | |
| f"of {val}."} | |
| order.append(root_id) | |
| chain = [root_id] | |
| for lvl in range(1, L): | |
| prev = chain[-1] | |
| adj, new_val = _unique_adj(artifacts[prev]["value"], spec0, met0) | |
| rid = new_id("d", lvl) | |
| prod = f"lab_{rng.choice('bcdefg')}" | |
| lab = ("RETRACTED laboratory " + prod if lvl == retracted_idx | |
| else "laboratory " + prod) | |
| artifacts[rid] = { | |
| "type": "derived", "specimen": spec0, "metric": met0, | |
| "value": new_val, "adjustment": adj, | |
| "parent": prev, "producer": prod, | |
| "retracted": lvl == retracted_idx, | |
| "text": (f"Derived note ({lab}): {spec0} {met0} " | |
| f"after adjustment {adj:+d} applied to the recorded " | |
| f"{met0} claim reads {new_val}.")} | |
| artifacts[rid]["text"] = artifacts[rid]["text"].replace( | |
| "laboratory :", "").replace(" ", " ") | |
| order.append(rid) | |
| chain.append(rid) | |
| # retracted node: everything downstream is invalid | |
| retracted_id = chain[retracted_idx] | |
| artifacts[retracted_id]["producer"] = "lab_retracted" | |
| artifacts[retracted_id]["text"] = artifacts[retracted_id]["text"].replace( | |
| "laboratory", "RETRACTED laboratory").replace( | |
| "RETRACTED LABORATORY", "RETRACTED laboratory") | |
| # --- F downstream branches hang below the retracted artifact | |
| def extend_branch(parent_id, length, branch_tag): | |
| cur = parent_id | |
| for i in range(length): | |
| adj, new_val = _unique_adj(artifacts[cur]["value"], spec0, met0) | |
| rid = new_id("d", i) | |
| artifacts[rid] = { | |
| "type": "derived", "specimen": spec0, "metric": met0, | |
| "value": new_val, "adjustment": adj, "parent": cur, | |
| "producer": f"lab_{rng.choice('bcdefg')}", "retracted": False, | |
| "text": f"Derived note (laboratory): {spec0} {met0} after " | |
| f"adjustment {adj:+d} applied to the recorded {met0} " | |
| f"claim reads {new_val}."} | |
| order.append(rid) | |
| cur = rid | |
| return cur | |
| poisoned_leaves = [extend_branch(retracted_id, max(1, L - retracted_idx), | |
| f"poison{b}") for b in range(F)] | |
| # --- clean branches: independent chains from other sources, same length | |
| clean_leaves = [] | |
| for _ in range(P * C): # one clean lineage per candidate conclusion | |
| sp = rng.choice([s for s in specimens if s != spec0]) | |
| me = rng.choice(metrics) | |
| # source value must also be unique for this (specimen, metric): a | |
| # duplicate would give some later adjusted note two earlier notes | |
| # sharing its parent value | |
| v = rng.randrange(5, 100) | |
| while any(a["specimen"] == sp and a["metric"] == me | |
| and a["value"] == v for a in artifacts.values()): | |
| v = rng.randrange(5, 100) | |
| sid = new_id("s", len(order)) | |
| artifacts[sid] = {"type": "source", "specimen": sp, "metric": me, | |
| "value": v, "producer": "lab_alpha", | |
| "parent": None, "retracted": False, | |
| "text": f"Source note: {sp} has baseline {me} of {v}."} | |
| order.append(sid) | |
| cur = sid | |
| for lvl in range(1, L): | |
| adj, nv = _unique_adj(artifacts[cur]["value"], sp, me) | |
| rid = new_id("d", lvl) | |
| artifacts[rid] = { | |
| "type": "derived", "specimen": sp, "metric": me, | |
| "value": nv, "adjustment": adj, "parent": cur, | |
| "producer": f"lab_{rng.choice('bcdefg')}", "retracted": False, | |
| "text": f"Derived note (laboratory): {sp} {me} after " | |
| f"adjustment {adj:+d} applied to the recorded {me} " | |
| f"claim reads {nv}."} | |
| order.append(rid) | |
| cur = rid | |
| clean_leaves.append(cur) | |
| # --- decoys: nearby values around derived notes (ambiguity A) | |
| # For each derived artifact, add A-1 decoy notes with the same | |
| # specimen+metric but values that do NOT satisfy any stated transform. | |
| base = len(artifacts) | |
| for aid in [a for a in order if artifacts[a]["type"] == "derived"]: | |
| for j in range(max(0, A - 1)): | |
| sp = artifacts[aid]["specimen"] | |
| me = artifacts[aid]["metric"] | |
| v = artifacts[aid]["value"] + rng.choice([-3, -2, 2, 3, 5, -5]) | |
| did = new_id("x", j) | |
| artifacts[did] = {"type": "derived", "specimen": sp, "metric": me, | |
| "value": v, "adjustment": None, "parent": None, | |
| "producer": f"lab_{rng.choice('bcdefg')}", | |
| "retracted": False, | |
| "text": f"Derived note (laboratory): {sp} {me} " | |
| f"after an adjustment applied to the " | |
| f"recorded {me} claim reads {v}."} | |
| order.append(did) | |
| # ambiguity A is realised by the decoy density above; the unique-parent | |
| # property of true derivations is preserved by construction. | |
| # --- conclusions: for each question, C candidates, one clean | |
| questions = {} | |
| for q in range(P): | |
| clean_leaf = clean_leaves[q] | |
| poisoned = rng.choice(poisoned_leaves) | |
| qid = f"q{q+1}" | |
| cands = [] | |
| clean_slot = rng.randrange(C) # exactly one clean candidate per question | |
| for c in range(C): | |
| cid = new_id("c", c) | |
| if c == clean_slot: # clean candidate | |
| artifacts[cid] = { | |
| "type": "conclusion", "question": qid, | |
| "answer": f"answer-{rng.randrange(10,99)}", | |
| "support_claim": clean_leaf, "parent": None, | |
| "producer": f"lab_{rng.choice('bcdefg')}", | |
| "retracted": False, | |
| "text": f"Conclusion: candidate {cid} answers question " | |
| f"{qid}; it is supported by the claim recorded in " | |
| f"artifact {clean_leaf}."} | |
| valid = True | |
| else: # candidate resting on the poisoned branch | |
| artifacts[cid] = { | |
| "type": "conclusion", "question": qid, | |
| "answer": f"answer-{rng.randrange(10,99)}", | |
| "support_claim": poisoned, "parent": None, | |
| "producer": f"lab_{rng.choice('bcdefg')}", | |
| "retracted": False, | |
| "text": f"Conclusion: candidate {cid} answers question " | |
| f"{qid}; it is supported by the claim recorded in " | |
| f"artifact {poisoned}."} | |
| valid = False | |
| order.append(cid) | |
| cands.append((cid, valid)) | |
| # exactly one clean candidate per question | |
| questions[qid] = cands | |
| answer_key = {q: next(cid for cid, ok in cands if ok) | |
| for q, cands in questions.items()} | |
| return {"artifacts": artifacts, "order": order, "questions": questions, | |
| "answer_key": answer_key, "P": P, "C": C} | |
| def artifact_text(a): | |
| return json.dumps({k: v for k, v in a.items() if k != "text"}, | |
| ensure_ascii=False) + " || " + a["text"] | |
| def catalog_rows(archive, attribution): | |
| rows = [] | |
| for aid in archive["order"]: | |
| a = archive["artifacts"][aid] | |
| row = {"id": aid, "type": a["type"], "title": a["text"][:60]} | |
| if a["type"] == "conclusion": | |
| row["question_id"] = a["question"] | |
| row["candidate_answer"] = a["answer"] | |
| if attribution: | |
| row["producer"] = a["producer"] | |
| row["parent"] = a["parent"] | |
| rows.append(row) | |
| return rows | |
| def system_prompt(k, rows, peer_obs): | |
| peer_txt = "" | |
| if peer_obs: | |
| peer_txt = ("\n\nOBSERVATIONS FROM EARLIER WORKERS on this same " | |
| "archive (read-only):\n" + peer_obs + | |
| "\nTheir submitted answers are also recorded above.") | |
| return f"""You are an evidence-checking worker. | |
| THE ARCHIVE: source notes (numerical claims about specimens), derived notes | |
| (each applies a stated signed adjustment to one earlier claim and reports the | |
| result), and candidate conclusions (each says which question it answers and | |
| which claim supports it). An artifact is VALID only if its producer is not | |
| retracted AND every artifact in its ancestry is valid. Some derived notes are | |
| decoys: only one preceding note's specimen, metric and value make each stated | |
| adjustment correct, so a note's true parent is unique. | |
| YOUR TASK: for each question, decide which candidate conclusion has a fully | |
| clean lineage. Exactly one candidate per question is clean. | |
| THE CATALOG below lists every artifact's ID, type and title. | |
| TOOLS (reply with exactly one JSON object per turn): | |
| {{"tool": "read_artifacts", "args": {{"artifact_ids": ["<id>", ...]}}}} | |
| - Returns full text of the requested artifacts; costs ONE read per artifact. | |
| {{"tool": "submit_answers", "args": {{"answers": {{"<question_id>": "<artifact_id>"}}}}}} | |
| - Submit one candidate per question; ends the episode. | |
| {{"tool": "yield_worker", "args": {{"summary": "..."}}}} ends the episode. | |
| READ BUDGET: exactly {k} artifact reads. | |
| {peer_txt} | |
| CATALOG: | |
| {json.dumps(rows, indent=1)} | |
| """ | |
| def run_condition(client, out_root, seed, L, A, F, treatment, usage=None, | |
| P=4, C=2, n_workers=4): | |
| """treatment: 'attribution' or 'no_attribution'.""" | |
| archive = generate_archive(seed, P=P, C=C, L=L, A=A, F=F) | |
| archive_size = len(archive["order"]) | |
| k = (archive_size + n_workers - 1) // n_workers | |
| attribution = treatment == "attribution" | |
| rows = catalog_rows(archive, attribution) | |
| run_dir = os.path.join(out_root, | |
| f"evidence_L{L}_A{A}_F{F}_{treatment}_seed{seed}") | |
| os.makedirs(run_dir, exist_ok=True) | |
| with open(os.path.join(run_dir, "archive.json"), "w") as f: | |
| json.dump({"artifacts": archive["artifacts"], | |
| "order": archive["order"], | |
| "answer_key": archive["answer_key"], | |
| "L": L, "A": A, "F": F}, f) | |
| shared_obs = [] # every artifact text read by every worker | |
| submissions = [] | |
| read_union = set() | |
| result_reads = None # unique reads before first exact submission | |
| for w in range(n_workers): | |
| wdir = os.path.join(run_dir, f"worker_{w}") | |
| os.makedirs(wdir, exist_ok=True) | |
| obs_path = os.path.join(wdir, "observations.jsonl") | |
| state = {"reads": 0, "submitted": None, "read_ids": []} | |
| def read_artifacts(args): | |
| ids = [str(i) for i in (args.get("artifact_ids") or [])] | |
| if not ids: | |
| return "ERROR: artifact_ids must be a non-empty list.", False | |
| if state["reads"] >= k: | |
| return ("ERROR: read budget exhausted. Call submit_answers " | |
| "now."), False | |
| unknown = [i for i in ids if i not in archive["artifacts"]] | |
| if unknown: | |
| return f"ERROR: unknown artifact ids: {unknown}", False | |
| charge = min(len(ids), k - state["reads"]) | |
| granted = ids[:charge] | |
| state["reads"] += charge | |
| state["read_ids"].extend(granted) | |
| texts = {i: artifact_text(archive["artifacts"][i]) | |
| for i in granted} | |
| for i in granted: | |
| entry = {"id": i, "text": texts[i]} | |
| shared_obs.append(entry) | |
| read_union.add(i) | |
| with open(obs_path, "a") as f: | |
| f.write(json.dumps(entry) + "\n") | |
| if len(ids) > len(granted): | |
| texts["_note"] = "budget exhausted; remaining ids not returned" | |
| return json.dumps(texts), False | |
| def submit(args): | |
| state["submitted"] = args.get("answers", {}) | |
| return "Answers recorded.", True | |
| def yield_worker(args): | |
| state["summary"] = args.get("summary", "") | |
| return "Episode committed.", True | |
| peer_txt = "" | |
| if shared_obs: | |
| peer_txt = json.dumps(shared_obs)[:20000] | |
| if submissions: | |
| peer_txt += "\nEARLIER SUBMISSIONS: " + json.dumps(submissions) | |
| tools = {"read_artifacts": read_artifacts, "submit_answers": submit, | |
| "yield_worker": yield_worker} | |
| prompt = system_prompt(k, rows, peer_txt) | |
| done = run_worker_episode(prompt, tools, usage=usage, client=client) | |
| if state["submitted"]: | |
| submissions.append({"worker": w, "answers": state["submitted"]}) | |
| exact = state["submitted"] == archive["answer_key"] | |
| submissions[-1]["exact"] = exact | |
| if exact and result_reads is None: | |
| result_reads = len(read_union) | |
| break | |
| frac = (result_reads / archive_size) if result_reads is not None else None | |
| return {"task": "evidence", "seed": seed, "L": L, "A": A, "F": F, | |
| "treatment": treatment, "archive_size": archive_size, "k": k, | |
| "reads_before_first_exact": result_reads, | |
| "fraction_read": frac, | |
| "n_workers_used": len(submissions) if result_reads is not None | |
| else n_workers, | |
| "any_exact": result_reads is not None, | |
| "run_dir": run_dir} |