Implicit-Reasoning-checkpoints / code-release /generate_multihop_from_atoms.py
fhyfhy's picture
Add code-release/
3970207 verified
Raw History Blame Contribute Delete
4.65 kB
#!/usr/bin/env python3
"""Build the mixed 2-hop + 3-hop two-graph dataset (App. A.2) from the atomic facts
of the symbolic two-hop dataset written by data_preparation.py.
Reads the atoms (target_text length 3) from <src>/train.json, reconstructs the
two graphs' adjacency, and writes a new dataset directory:
train.json : all atoms (A+B) + --train-2hop A 2-hops + --train-3hop A 3-hops
test_id.json : held-out A 2-hops + A 3-hops (disjoint from train)
test_ood.json : B 2-hops + B 3-hops
valid.json : []
vocab.json : copied from the source dataset
manifest.json : counts + generation config
Usage:
python generate_multihop_from_atoms.py \
--src data/twin_twohop_truood_diff.500.50.10 \
--out data/twin_23hop_truood_diff.500.50.10
"""
import argparse
import json
import random
import shutil
from collections import defaultdict
from pathlib import Path
# Held-out graph-A (ID) and graph-B (OOD) eval samples per hop. All splits are drawn
# from one RNG stream, so changing this also changes the 3-hop training samples.
EVAL_PER_HOP = 2000
def load_atoms(train_path: Path):
data = json.loads(train_path.read_text())
atoms = [x for x in data if len(x["target_text"]) == 3]
adj = defaultdict(dict) # head -> {rel: tail}
for x in atoms:
head, rel, tail = x["target_text"]
adj[head][rel] = tail
return atoms, adj
def graph_heads(adj, prefix):
return sorted(h for h in adj if h.startswith(prefix))
def make_record(head, rels, tail, hops, graph):
return {
"input_text": [head, *rels],
"target_text": [head, *rels, tail],
"type": f"{hops}hop-{graph}",
}
def sample_paths(adj, heads, hops, count, rng):
"""Uniformly sample `count` distinct hop-paths (every entity has the same
out-degree, so independent uniform picks per step are uniform over paths)."""
seen = set()
out = []
while len(out) < count:
head = rng.choice(heads)
rels = []
cur = head
for _ in range(hops):
r = rng.choice(sorted(adj[cur]))
rels.append(r)
cur = adj[cur][r]
key = (head, *rels)
if key in seen:
continue
seen.add(key)
out.append((head, tuple(rels), cur))
return out
def main():
ap = argparse.ArgumentParser(description="Build the mixed 2-hop + 3-hop dataset from symbolic atoms.")
ap.add_argument("--src", type=Path, required=True, help="source two-hop dataset directory")
ap.add_argument("--out", type=Path, required=True, help="output dataset directory")
ap.add_argument("--seed", type=int, default=7)
ap.add_argument("--train-2hop", type=int, default=5000, help="graph-A 2-hop training samples")
ap.add_argument("--train-3hop", type=int, default=5000, help="graph-A 3-hop training samples")
args = ap.parse_args()
rng = random.Random(args.seed)
atoms, adj = load_atoms(args.src / "train.json")
heads_a = graph_heads(adj, "<a_")
heads_b = graph_heads(adj, "<b_")
print(f"atoms={len(atoms)} A-heads={len(heads_a)} B-heads={len(heads_b)}")
train_hop_counts = {h: n for h, n in ((2, args.train_2hop), (3, args.train_3hop)) if n > 0}
train, test_id, test_ood = list(atoms), [], []
for hops in sorted(train_hop_counts):
n_train, n_id = train_hop_counts[hops], EVAL_PER_HOP
picked = sample_paths(adj, heads_a, hops, n_train + n_id, rng)
train += [make_record(h, r, t, hops, "A") for h, r, t in picked[:n_train]]
test_id += [make_record(h, r, t, hops, "A") for h, r, t in picked[n_train:]]
picked_b = sample_paths(adj, heads_b, hops, EVAL_PER_HOP, rng)
test_ood += [make_record(h, r, t, hops, "B") for h, r, t in picked_b]
args.out.mkdir(parents=True, exist_ok=True)
(args.out / "train.json").write_text(json.dumps(train))
(args.out / "test_id.json").write_text(json.dumps(test_id))
(args.out / "test_ood.json").write_text(json.dumps(test_ood))
(args.out / "valid.json").write_text("[]")
shutil.copy(args.src / "vocab.json", args.out / "vocab.json")
manifest = {
"source": str(args.src),
"seed": args.seed,
"train": {"atoms": len(atoms), **{f"{k}hop_A": v for k, v in train_hop_counts.items()}},
"test_id": {f"{k}hop_A": EVAL_PER_HOP for k in train_hop_counts},
"test_ood": {f"{k}hop_B": EVAL_PER_HOP for k in train_hop_counts},
}
(args.out / "manifest.json").write_text(json.dumps(manifest, indent=2))
print(f"train={len(train)} test_id={len(test_id)} test_ood={len(test_ood)} -> {args.out}")
if __name__ == "__main__":
main()