File size: 7,635 Bytes
74b7543
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
"""Build a mixed 2-hop + 3-hop twin-graph dataset from the atomic facts of an
existing twin_twohop dataset.

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) + N_TRAIN_2HOP A 2-hops + N_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

EVAL_PER_HOP = 2000  # held-out graph-A (ID) and graph-B (OOD) eval samples per hop


def path_key(record):
    return tuple(record["target_text"][:-1])  # (head, r_1..r_k)


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 walk(adj, head, rels):
    cur = head
    for r in rels:
        cur = adj[cur][r]
    return cur


def sample_paths(adj, heads, hops, count, rng, exclude=None):
    """Uniformly sample `count` distinct hop-paths (every entity has the same
    out-degree, so independent uniform picks per step are uniform over paths)."""
    exclude = exclude or set()
    seen = set(exclude)
    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()
    ap.add_argument("--src", type=Path, required=True)
    ap.add_argument("--out", type=Path, required=True)
    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")
    ap.add_argument("--train-4hop", type=int, default=0, help="graph-A 4-hop training samples (0 = no 4-hop)")
    ap.add_argument("--train-5hop", type=int, default=0, help="graph-A 5-hop training samples (0 = no 5-hop)")
    ap.add_argument(
        "--eval-hops",
        type=str,
        default="",
        help="Comma-separated hop depths to build EVAL-ONLY splits for (e.g. '6'): ID chains from "
             "graph A and OOD chains from graph B, with no training data at those depths.",
    )
    ap.add_argument("--no-train", action="store_true", help="write only the eval splits (no train.json)")
    ap.add_argument(
        "--reuse-eval-from",
        type=Path,
        default=None,
        help=(
            "Reuse test_id.json/test_ood.json from this dataset dir so the shared hop counts "
            "stay directly comparable; hops present only in the new dataset get freshly sampled "
            "eval sets. Train sampling excludes every reused ID path."
        ),
    )
    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),
            (4, args.train_4hop), (5, args.train_5hop),
        ) if n > 0
    }
    train, test_id, test_ood = list(atoms), [], []

    if args.reuse_eval_from is not None:
        test_id = json.loads((args.reuse_eval_from / "test_id.json").read_text())
        test_ood = json.loads((args.reuse_eval_from / "test_ood.json").read_text())
        id_keys_by_hops = {}
        for rec in test_id:
            id_keys_by_hops.setdefault(len(rec["target_text"]) - 2, set()).add(path_key(rec))
        for hops in sorted(train_hop_counts):
            if hops not in id_keys_by_hops:
                # hop count absent from the reused eval -> sample fresh ID/OOD sets for it
                fresh_id = sample_paths(adj, heads_a, hops, EVAL_PER_HOP, rng)
                test_id += [make_record(h, r, t, hops, "A") for h, r, t in fresh_id]
                id_keys_by_hops[hops] = {(h, *r) for h, r, _ in fresh_id}
                fresh_ood = sample_paths(adj, heads_b, hops, EVAL_PER_HOP, rng)
                test_ood += [make_record(h, r, t, hops, "B") for h, r, t in fresh_ood]
            picked = sample_paths(
                adj, heads_a, hops, train_hop_counts[hops], rng,
                exclude=id_keys_by_hops.get(hops, set()),
            )
            train += [make_record(h, r, t, hops, "A") for h, r, t in picked]
    else:
        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]

    # eval-only depths: sampled from both graphs, never used for training
    eval_only = [int(h) for h in args.eval_hops.split(",") if h.strip()]
    for hops in eval_only:
        picked_a = sample_paths(adj, heads_a, hops, EVAL_PER_HOP, rng)
        test_id += [make_record(h, r, t, hops, "A") for h, r, t in picked_a]
        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]

    if args.no_train:
        train = []

    args.out.mkdir(parents=True, exist_ok=True)
    if not args.no_train:
        (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,
        "reuse_eval_from": str(args.reuse_eval_from) if args.reuse_eval_from else None,
        "train": {} if args.no_train else {"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 (list(train_hop_counts) + eval_only)},
        "test_ood": {f"{k}hop_B": EVAL_PER_HOP for k in (list(train_hop_counts) + eval_only)},
        "eval_only_hops": eval_only,
    }
    (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()