File size: 3,641 Bytes
a1cce80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Small, reproducible pointer-chasing data; no dataset download required."""

import hashlib
import itertools
import json
import random
from pathlib import Path

import torch

NODES = "ABCDEFGH"


def graph_pools():
    # All 7! directed cycles through eight nodes, canonicalized by starting at A.
    # Splitting *graphs* prevents memorizing a table seen in another split.
    pools = {"train": [], "validation": [], "test": []}
    for tail in itertools.permutations(NODES[1:]):
        cycle = ("A",) + tail
        mapping = dict(zip(cycle, cycle[1:] + cycle[:1]))
        graph_id = "".join(mapping[node] for node in NODES)
        bucket = int(hashlib.sha256(graph_id.encode()).hexdigest(), 16) % 10
        split = "train" if bucket < 8 else "validation" if bucket == 8 else "test"
        pools[split].append(graph_id)
    return pools


def make_split(pool, size, hops, seed):
    rng = random.Random(seed)
    # Sample without replacement in (graph, start, hops), even if row order varies.
    candidates = list(itertools.product(pool, NODES, hops))
    if not 0 < size <= len(candidates):
        raise ValueError(f"size must be in [1, {len(candidates)}]")
    records = []
    for graph_id, start, n_hops in rng.sample(candidates, size):
        mapping = dict(zip(NODES, graph_id))
        order = list(NODES)
        rng.shuffle(order)
        path = [start]
        for _ in range(n_hops):
            path.append(mapping[path[-1]])
        table = " ".join(f"{node}>{mapping[node]}" for node in order)
        prompt = f"{table}\nStart: {start}. Steps: {n_hops}. Answer:"
        records.append(dict(prompt=prompt, answer=" " + path[-1],
                            hops=n_hops, graph_id=graph_id, path=path))
    return records


def make_data(train_size=12000, eval_size=512, seed=42):
    pools = graph_pools()
    return {
        "train": make_split(pools["train"], train_size, (1, 2, 3), seed),
        "validation": make_split(pools["validation"], eval_size, (1, 2, 3), seed + 1),
        "test": make_split(pools["test"], eval_size, (1, 2, 3), seed + 2),
        "test_long": make_split(pools["test"], eval_size, (4, 5, 6), seed + 3),
    }


def save_data(splits, directory):
    directory = Path(directory)
    directory.mkdir(parents=True, exist_ok=True)
    for name, rows in splits.items():
        with (directory / f"{name}.jsonl").open("w") as f:
            for row in rows:
                f.write(json.dumps(row) + "\n")


class AnswerDataset(torch.utils.data.Dataset):
    def __init__(self, records, tokenizer):
        self.examples = []
        for row in records:
            prompt = tokenizer.encode(row["prompt"], add_special_tokens=False)
            answer = tokenizer.encode(row["answer"], add_special_tokens=False)
            if len(answer) != 1:
                raise ValueError("This experiment expects each answer to be one token")
            self.examples.append((prompt + answer, [-100] * len(prompt) + answer))

    def __len__(self):
        return len(self.examples)

    def __getitem__(self, index):
        return self.examples[index]


def collate(examples, pad_token_id):
    length = max(len(ids) for ids, _ in examples)
    input_ids = torch.full((len(examples), length), pad_token_id, dtype=torch.long)
    labels = torch.full_like(input_ids, -100)
    attention_mask = torch.zeros_like(input_ids)
    for i, (ids, target) in enumerate(examples):
        input_ids[i, :len(ids)] = torch.tensor(ids)
        labels[i, :len(ids)] = torch.tensor(target)
        attention_mask[i, :len(ids)] = 1
    return dict(input_ids=input_ids, attention_mask=attention_mask, labels=labels)