reza2ei's picture
Duplicate from reza2ei/Conditional_Causal_Difficulty_for_LLMs
a0d1de2
Raw History Blame Contribute Delete
8.5 kB
#!/usr/bin/env python
"""Build a mixed-no-op dataset by resampling existing audited multi-operator data.
No new LLM calls: for each base problem, draws --mix-twins twins at random
(seeded, reproducible), split as evenly as possible across the operator
families present for that problem ({sentence_reorder, entity_rename,
math_irrelevant_context}), and recomputes d_obs/d_wc over just the sampled
twins.
`--mix-twins` (m) is the TOTAL number of no-op twins per base problem, shared
uniformly across the operator families -- not a per-twin dosage. Because
math_irrelevant_context also has a per-twin "dosage" knob (how many
irrelevant sentences are stacked into a single twin, baked into sibling files
named ``..._m{dosage}_multi_..."``), this script picks the dosage whose
sibling file most closely matches that family's per-problem share of m, so a
twin drawn from that family carries roughly one injected sentence per "share
unit" rather than a fixed dosage unrelated to m. sentence_reorder and
entity_rename twins are always a single operator application (they carry no
stacking concept) and are read directly from --input.
Usage
-----
python scripts/build_multiop_mix.py \\
--input data_audited_multiop/gsmic_adv_m1_multi_4omini_labeled_pairs.jsonl \\
--output data_audited_multiop_mix/gsmic_adv_m9_multiop_mix_4omini_labeled_pairs.jsonl \\
--mix-twins 9 --seed 42
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import statistics
from pathlib import Path
from random import Random
IRRELEVANT_CONTEXT_PREFIX = "math_irrelevant_context"
DOSAGE_FILENAME_RE = re.compile(r"^(?P<prefix>.*_)m(?P<dosage>\d+)(?P<suffix>_multi_.*)$")
def _seeded_rng(base_id: str, seed: int) -> Random:
h = int(hashlib.md5(f"{seed}:mix:{base_id}".encode()).hexdigest(), 16)
return Random(h)
def _load_jsonl(path: Path) -> list[dict]:
return [json.loads(l) for l in path.read_text().splitlines() if l.strip()]
def _irrelevant_context_operator_name(dosage: int) -> str:
return IRRELEVANT_CONTEXT_PREFIX if dosage == 1 else f"{IRRELEVANT_CONTEXT_PREFIX}_m{dosage}"
def _discover_dosage_siblings(input_path: Path) -> dict[int, Path]:
"""Find sibling files that differ only in their m{dosage} component."""
m = DOSAGE_FILENAME_RE.match(input_path.name)
if not m:
return {}
siblings: dict[int, Path] = {}
for candidate in input_path.parent.glob(f"{m.group('prefix')}m*{m.group('suffix')}"):
cm = DOSAGE_FILENAME_RE.match(candidate.name)
if cm:
siblings[int(cm.group("dosage"))] = candidate
return siblings
def _nearest_dosage(share: int, available: list[int]) -> int:
"""Closest available dosage to `share`; ties broken toward the larger dosage."""
return min(available, key=lambda d: (abs(d - share), -d))
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--input", required=True, help="Source audited multi-operator .jsonl")
ap.add_argument("--output", required=True, help="Destination .jsonl for the mixed dataset")
ap.add_argument("--mix-twins", type=int, default=9,
help="Total number of twins to sample per base problem, "
"split evenly across operator families (default: 9)")
ap.add_argument("--seed", type=int, default=42,
help="Seed for reproducible per-problem sampling (default: 42)")
args = ap.parse_args()
in_path = Path(args.input)
out_path = Path(args.output)
base_records = _load_jsonl(in_path)
dosage_files = _discover_dosage_siblings(in_path)
available_dosages = sorted(dosage_files) or [1]
dosage_records_cache: dict[int, list[dict]] = {}
def records_for_dosage(dosage: int) -> list[dict]:
if dosage not in dosage_records_cache:
path = dosage_files.get(dosage, in_path)
dosage_records_cache[dosage] = _load_jsonl(path)
return dosage_records_cache[dosage]
by_base: dict[str, list[dict]] = {}
for r in base_records:
by_base.setdefault(r["base_id"], []).append(r)
# base_id -> dosage -> operator -> rows, populated lazily as dosages are needed.
irrelevant_pool_cache: dict[int, dict[str, list[dict]]] = {}
def irrelevant_pool(dosage: int, base_id: str) -> list[dict]:
by_base_for_dosage = irrelevant_pool_cache.get(dosage)
if by_base_for_dosage is None:
by_base_for_dosage = {}
op_name = _irrelevant_context_operator_name(dosage)
for r in records_for_dosage(dosage):
if r["operator"] == op_name:
by_base_for_dosage.setdefault(r["base_id"], []).append(r)
irrelevant_pool_cache[dosage] = by_base_for_dosage
return by_base_for_dosage.get(base_id, [])
out_records: list[dict] = []
n_short = 0
dosage_used_counts: dict[int, int] = {}
for base_id, rows in by_base.items():
rng = _seeded_rng(base_id, args.seed)
by_op: dict[str, list[dict]] = {}
for r in rows:
by_op.setdefault(r["operator"], []).append(r)
ops = sorted(by_op.keys())
n_ops = len(ops)
# Split mix_twins evenly across the operator families present for this
# problem, then randomly sample within each family -- keeps the mix
# uniform across families instead of skewed toward whichever family
# happens to have the largest twin pool.
base_share, remainder = divmod(args.mix_twins, n_ops)
shares = {op: base_share for op in ops}
for op in rng.sample(ops, remainder):
shares[op] += 1
sampled: list[dict] = []
for op in ops:
share = shares[op]
if share == 0:
continue
if op.startswith(IRRELEVANT_CONTEXT_PREFIX):
dosage = _nearest_dosage(share, available_dosages)
pool = irrelevant_pool(dosage, base_id)
dosage_used_counts[dosage] = dosage_used_counts.get(dosage, 0) + min(share, len(pool))
else:
pool = by_op[op]
k = min(share, len(pool))
sampled.extend(rng.sample(pool, k))
if len(sampled) < args.mix_twins:
n_short += 1
deltas = [r["delta_mean"] for r in sampled]
d_avg = float(statistics.fmean(deltas)) if deltas else 0.0
d_wc = float(max(deltas)) if deltas else 0.0
for r in sampled:
r = dict(r) # don't mutate the source record
r["d_obs"] = d_avg
r["d_wc"] = d_wc
out_records.append(r)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text("\n".join(json.dumps(r) for r in out_records) + "\n")
op_counts: dict[str, int] = {}
for r in out_records:
op_counts[r["operator"]] = op_counts.get(r["operator"], 0) + 1
meta = {
"dataset": "gsmic_adv_multiop_mix",
"source_file": str(in_path),
"mix_operator": True,
"mix_twins": args.mix_twins,
"seed": args.seed,
"n_base_problems": len(by_base),
"n_pairs": len(out_records),
"n_base_problems_with_fewer_than_mix_twins": n_short,
"operator_counts": op_counts,
"irrelevant_context_dosage_files": {str(d): str(p) for d, p in sorted(dosage_files.items())},
"irrelevant_context_dosage_twin_counts": {str(d): c for d, c in sorted(dosage_used_counts.items())},
"note": "Resampled from an existing audited multi-operator run; no new LLM calls. "
"mix_twins is the total no-op twin count per problem, split evenly across "
"families; math_irrelevant_context twins are drawn from the dosage-matched "
"sibling file for that family's per-problem share.",
}
(out_path.parent / (out_path.stem.replace("_labeled_pairs", "") + ".meta.json")).write_text(
json.dumps(meta, indent=2) + "\n"
)
print(f"Wrote {len(out_records)} pairs ({len(by_base)} base problems) -> {out_path}")
print(f"Operator mix: {op_counts}")
print(f"Irrelevant-context dosage usage: {dosage_used_counts}")
if n_short:
print(f"WARNING: {n_short} base problems had fewer than {args.mix_twins} "
"available twins in the source file and were short-sampled.")
if __name__ == "__main__":
main()