File size: 5,298 Bytes
3970207
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Build the symbolic two-graph two-hop dataset (Sec. 3.1).

The graphs G_A and G_B have disjoint entity sets and share one relation vocabulary.
Every entity has `--out-degree` outgoing edges labeled by distinct relations, each
pointing to a uniformly random entity of the same graph. The edges of G_A and G_B are
sampled independently (seeds `--seed` and `--seed + 1`).

  train.json : all atomic facts of G_A and G_B + all two-hop chains of G_A
  test.json  : all two-hop chains of G_B (type "TwoHop-B")
  valid.json : empty
  vocab.json : entity tokens of both graphs, relation tokens, special tokens

The trainer samples the two-hop training questions and the ID test set from the G_A
chains in train.json, and the OOD test set from test.json.

Adapted from the dataset code of Ye et al. (2025), "How do transformers learn implicit reasoning?".
"""
from __future__ import annotations

import argparse
import json
from copy import deepcopy
from pathlib import Path
from typing import Iterable, List, Tuple

import numpy as np
from tqdm.auto import tqdm


# Not used in the samples, but part of vocab.json and hence of the model vocabulary.
SPECIAL_TOKENS = ["<mask>", "<sep>", "<a>", "<q>", "</q>"]


def form_items(context_tokens: Iterable[str], target_token: str):
    input_tokens = list(context_tokens)
    target_tokens = input_tokens + [target_token]
    return {"input_text": input_tokens, "target_text": target_tokens}


def write_json(path: Path, payload):
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as f:
        json.dump(payload, f)


def build_vocab(entities: List[str], relations: List[str]) -> List[str]:
    vocab: List[str] = []
    vocab.extend(entities)
    vocab.extend(relations)
    vocab.extend(SPECIAL_TOKENS)
    return vocab


def build_twin_twohop_truood_diff(
    num_entities: int, num_relations: int, out_degree: int, seed: int, out_dir: Path
) -> Path:
    """Sample G_A and G_B and write train/valid/test/vocab.json to `out_dir`."""
    rng_a = np.random.default_rng(seed)
    rng_b = np.random.default_rng(seed + 1)
    base_entities = list(range(num_entities))
    relations = [f"<r_{i}>" for i in range(num_relations)]

    def sample_edges(rng: np.random.Generator, desc: str):
        edges = []
        for i in tqdm(base_entities, desc=desc):
            selected_rows = rng.choice(num_relations, size=out_degree, replace=False).tolist()
            for row_idx in selected_rows:
                col_idx = rng.integers(num_entities)
                edges.append((i, row_idx, col_idx))
        return edges

    edges_a = sample_edges(rng_a, "atomics-a")
    edges_b = sample_edges(rng_b, "atomics-b")

    def materialize(prefix: str, edges: List[Tuple[int, int, int]]):
        ents = [f"<{prefix}_e_{i}>" for i in base_entities]
        atomic_dict = {}
        atomic_facts = []
        for h_idx, r_idx, t_idx in edges:
            h, r, t = ents[h_idx], relations[r_idx], ents[t_idx]
            atomic_facts.append(form_items([h, r], t))
            atomic_dict.setdefault(h, []).append((r, t))
        twohop = []
        for h in ents:
            for (r1, b) in atomic_dict[h]:
                for (r2, t) in atomic_dict[b]:
                    twohop.append(form_items([h, r1, r2], t))
        return ents, atomic_facts, twohop

    ents_a, atom_a, twohop_a = materialize("a", edges_a)
    ents_b, atom_b, twohop_b = materialize("b", edges_b)

    vocab = build_vocab(ents_a + ents_b, relations)
    train = atom_a + atom_b + twohop_a
    probes = []
    for item in twohop_b:
        cur = deepcopy(item)
        cur["type"] = "TwoHop-B"
        probes.append(cur)

    out_dir.mkdir(parents=True, exist_ok=True)
    write_json(out_dir / "train.json", train)
    write_json(out_dir / "valid.json", [])
    write_json(out_dir / "test.json", probes)
    write_json(out_dir / "vocab.json", vocab)
    return out_dir


def parse_args():
    parser = argparse.ArgumentParser(description="Build the symbolic two-graph two-hop dataset.")
    parser.add_argument("--num-entities", type=int, default=500, help="Entities per graph.")
    parser.add_argument("--num-relations", type=int, default=50, help="Relations shared by both graphs.")
    parser.add_argument("--out-degree", type=int, default=10, help="Outgoing relations per entity.")
    parser.add_argument("--seed", type=int, default=7, help="Seed of G_A; G_B uses seed + 1.")
    parser.add_argument(
        "--output-root",
        type=Path,
        default=Path(__file__).resolve().parent / "data",
        help="Where to write the dataset directory.",
    )
    parser.add_argument(
        "--dataset-name",
        type=str,
        default=None,
        help="Dataset directory name (default: twin_twohop_truood_diff.<entities>.<relations>.<out-degree>).",
    )
    return parser.parse_args()


def main():
    args = parse_args()
    dataset_name = args.dataset_name or (
        f"twin_twohop_truood_diff.{args.num_entities}.{args.num_relations}.{args.out_degree}"
    )
    out_dir = build_twin_twohop_truood_diff(
        args.num_entities, args.num_relations, args.out_degree, args.seed, args.output_root / dataset_name
    )
    print(f"Wrote dataset to {out_dir}")


if __name__ == "__main__":
    main()