chiron-data / code /measurement /build_interventions.py
henry-yeh's picture htr234234's picture
Chiron data release
1b86964
Raw History Blame Contribute Delete
12.7 kB
#!/usr/bin/env python3
"""Rebuild the controlled-intervention evaluation inputs without model calls.
python code/measurement/build_interventions.py
python code/measurement/build_interventions.py --include-real-records
python code/measurement/build_interventions.py --include-real-records --public-only
The default builds questionnaire.jsonl and narrative.jsonl. The optional real
record build reads prepared PANDORA samples supplied by the user; --public-only
keeps DASS and IPIP-FFM backgrounds without requiring PANDORA. Fixed selections
and baseline prompts reproduce the distributed format. Source files and training
data are unchanged.
"""
from __future__ import annotations
import argparse
from collections import Counter
import json
import math
from pathlib import Path
import re
from build_bias import messages, read_json, select_rows
from build_human_gold import write_rows
from build_item_response import load_schema
ROOT = Path(__file__).resolve().parents[2]
DATA = ROOT / "data/eval/measurement_interventions"
POOL = ROOT / "data/intermediate/measurement/llm_intensity/candidate_intensities.jsonl"
PANDORA = ROOT / "data/raw/measurement/human_gold/pandora/samples.jsonl"
def read_rows(path):
with Path(path).open(encoding="utf-8") as handle:
for line in handle:
if line.strip():
yield json.loads(line)
def load_candidates(design):
required = set()
for group in design["narrative"]["groups"]:
for pair in group["pairs"]:
required.update((pair["low"], pair["high"]))
for group in design["real_records"]["groups"]:
required.update((group["low"], group["high"]))
candidates = {}
for row in read_rows(POOL):
key = row["candidate_id"]
if key not in required:
continue
if key in candidates:
raise ValueError(f"Duplicate candidate ID: {key}")
score = row["fitted_intensity_cc_mean0"]
if not math.isfinite(score) or not row["text"].strip():
raise ValueError(f"Invalid narrative candidate: {key}")
candidates[key] = row
if set(candidates) != required:
raise ValueError(f"Missing {len(required - candidates.keys())} narrative candidates")
return candidates
def checked_pair(pair, construct_id, candidates):
low, high = candidates[pair["low"]], candidates[pair["high"]]
if low["construct_id"] != construct_id or high["construct_id"] != construct_id:
raise ValueError("Narrative construct does not match the intervention target")
if not low["fitted_intensity_cc_mean0"] < 0 < high["fitted_intensity_cc_mean0"]:
raise ValueError("Expected a negative/positive narrative pair")
return low, high
def build_questionnaire(schema, names):
bias = read_json(ROOT / "data/eval/measurement_bias/sources/design.json")
design = bias["context_and_order"]
specs = bias["items"]
texts = {item["item_id"]: item["text"] for item in schema["items"]}
templates = schema["response_scale_templates"]
def render(key, level):
spec = specs[key]
template = templates[spec["response_scale"]]
points = int(template["points"])
if level == 0:
if points % 2 != 1:
raise ValueError(f"No midpoint response for {key}")
response = (points + 1) // 2
else:
response = points if level * spec["direction"] > 0 else 1
clause = re.sub(r"\s+", " ", texts[spec["item_id"]]).strip().rstrip(".")
return (template["naturalization_templates"][response - 1]
.replace("{item_clause}", clause).replace("{item_task}", clause))
rows = []
for index, group in enumerate(design["groups"], 1):
cid = group["construct_id"]
targets, fillers = group["target_items"], group["filler_items"]
if len(targets) != 3 or len(fillers) != 3:
raise ValueError("Expected three target items and three filler items")
if (any(specs[key]["construct_id"] != cid for key in targets)
or any(specs[key]["construct_id"] == cid for key in fillers)):
raise ValueError("Invalid target/filler assignment")
neutral = [render(key, 0) for key in fillers]
conditions = {}
for dose in range(4):
levels = [1 if i < dose else -1 for i in range(3)]
evidence = [render(key, level) for key, level in zip(targets, levels)]
records = [text for pair in zip(evidence, neutral) for text in pair]
conditions[f"dose{dose}"] = {
"messages": messages(design["system"], design["record_context"],
records, assistant=True),
"target_level": sum(levels) / 3,
}
rows.append({"sample_id": f"questionnaire:{index:04d}",
"construct_id": cid, "construct": names[cid], "conditions": conditions})
counts = Counter(row["construct_id"] for row in rows)
if set(counts) != set(names) or set(counts.values()) != {5}:
raise ValueError("Expected five questionnaire groups per construct")
return rows
def build_narrative(design, names, candidates):
config = design["narrative"]
if len(config["fillers"]) != 3:
raise ValueError("Expected three fixed background statements")
rows = []
for group in config["groups"]:
cid = group["construct_id"]
if len(group["pairs"]) != 3:
raise ValueError("Expected three narrative pairs per group")
pairs = [checked_pair(pair, cid, candidates) for pair in group["pairs"]]
conditions = {}
for dose in range(4):
selected = [pair[1] if i < dose else pair[0] for i, pair in enumerate(pairs)]
records = [text for pair in zip([r["text"] for r in selected], config["fillers"])
for text in pair]
conditions[f"dose{dose}"] = {
"messages": messages(config["system"], config["record_context"],
records, assistant=True),
"target_level": math.fsum(r["fitted_intensity_cc_mean0"] for r in selected) / 3,
}
rows.append({"sample_id": group["sample_id"], "construct_id": cid,
"construct": names[cid], "conditions": conditions})
counts = Counter(row["construct_id"] for row in rows)
if set(counts) != set(names) or set(counts.values()) != {3}:
raise ValueError("Expected three narrative groups per construct")
return rows
def load_backgrounds(design, pandora_source, public_only=False):
groups = design["real_records"]["groups"]
domains = ("openpsych_dass", "openpsych_ipip_ffm") if public_only else ("pandora", "openpsych_dass", "openpsych_ipip_ffm")
required = {
domain: {g["background"]["sample_id" if domain == "pandora" else "respondent_index"]
for g in groups if g["domain"] == domain}
for domain in domains
}
if not public_only and not pandora_source.is_file():
raise FileNotFoundError(
f"Missing prepared PANDORA samples: {pandora_source}. "
"See data/raw/measurement/human_gold/SOURCE.md and run "
"code/measurement/build_human_gold.py --prepare-source --domain pandora."
)
sources = {} if public_only else {"pandora": pandora_source}
for domain in ("openpsych_dass", "openpsych_ipip_ffm"):
sources[domain] = ROOT / "data/raw/prediction" / domain / "qa_jsonl/test.jsonl"
found = {domain: {} for domain in sources}
for domain, path in sources.items():
for row in read_rows(path):
if domain == "pandora":
if row.get("domain") != domain:
continue
key = row["sample_id"]
else:
key = row["extra_info"]["respondent_index"]
if key not in required[domain]:
continue
if row["split"] != "test" or key in found[domain]:
raise ValueError(f"Invalid or duplicate test background in {domain}: {key}")
found[domain][key] = row["observations"]
if set(found[domain]) != required[domain]:
raise ValueError(f"Missing selected backgrounds from {domain}")
return found
def build_real_records(design, names, candidates, pandora_source, public_only=False):
config = design["real_records"]
backgrounds = load_backgrounds(design, pandora_source, public_only=public_only)
rows = []
for group in config["groups"]:
cid, domain, spec = group["construct_id"], group["domain"], group["background"]
if public_only and domain == "pandora":
continue
key = spec["sample_id" if domain == "pandora" else "respondent_index"]
original = backgrounds[domain][key]
if len(original) != spec["source_record_count"]:
raise ValueError(f"Source record count differs for {group['sample_id']}")
if domain == "pandora":
indices = spec["record_indices"]
if (not indices or indices != sorted(set(indices))
or any(type(i) is not int or not 0 <= i < len(original) for i in indices)):
raise ValueError(f"Invalid record selection for {group['sample_id']}")
records = [original[i] for i in indices]
else:
records = list(original)
low, high = checked_pair(group, cid, candidates)
position = group["position"]
if position not in {"prepend", "append"}:
raise ValueError(f"Invalid insertion position: {position}")
conditions = {"background": {
"messages": messages(config["system"], config["record_context"], records),
}}
for condition, narrative in (("low", low), ("high", high)):
added = narrative["text"]
if added in records:
raise ValueError(f"Intervention already occurs in {group['sample_id']}")
modified = [added] + records if position == "prepend" else records + [added]
conditions[condition] = {
"messages": messages(config["system"], config["record_context"], modified),
"added_level": narrative["fitted_intensity_cc_mean0"],
}
rows.append({"sample_id": group["sample_id"], "domain": domain,
"construct_id": cid, "construct": names[cid],
"position": position, "conditions": conditions})
if Counter(r["domain"] for r in rows) != {domain: 200 for domain in backgrounds}:
raise ValueError("Expected 200 backgrounds per domain")
if Counter(r["position"] for r in rows) != {"prepend": len(rows) // 2, "append": len(rows) // 2}:
raise ValueError("Expected balanced prepend/append positions")
return rows
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--include-real-records", action="store_true",
help="Also build real-record inputs; full mode requires prepared PANDORA samples")
parser.add_argument("--public-only", action="store_true", help="Exclude PANDORA real-record backgrounds")
parser.add_argument("--output-dir", type=Path, default=DATA)
parser.add_argument("--pandora-source", type=Path,
help="Prepared PANDORA samples.jsonl (or combined human-gold samples.jsonl)")
args = parser.parse_args()
if args.pandora_source is not None and not args.include_real_records:
parser.error("--pandora-source requires --include-real-records")
vocab = read_json(ROOT / "data/raw/measurement/construct_vocab.json")
names = {int(cid): name for name, cid in vocab.items()}
design = read_json(DATA / "sources/design.json")
candidates = load_candidates(design)
outputs = {
"questionnaire.jsonl": build_questionnaire(load_schema(), names),
"narrative.jsonl": build_narrative(design, names, candidates),
}
if args.include_real_records:
outputs["real_records.jsonl"] = build_real_records(
design, names, candidates, args.pandora_source or PANDORA, public_only=args.public_only)
selections = read_json(ROOT / "data/eval/measurement_selections.json")
scoring = read_json(ROOT / "data/eval/measurement_scoring.json")
outputs = {filename: select_rows(rows, Path(filename).stem, selections, scoring, public_only=args.public_only)
for filename, rows in outputs.items()}
for filename, rows in outputs.items():
write_rows(args.output_dir / filename, rows)
print(f"{filename}: {len(rows):,} groups")
if __name__ == "__main__":
main()