Datasets:
Download source/data.py from ariG23498/looped-distilgpt2-pointer-chasing-5k-data: direct link, hf CLI and curl.
- Browser
- Download file 3.64 kB
-
https://huggingface.co/datasets/ariG23498/looped-distilgpt2-pointer-chasing-5k-data/resolve/main/source/data.py
- Command line
-
hf download hf://datasets/ariG23498/looped-distilgpt2-pointer-chasing-5k-data/source/data.py
-
curl -L -o data.py https://huggingface.co/datasets/ariG23498/looped-distilgpt2-pointer-chasing-5k-data/resolve/main/source/data.py
3.64 kB
| """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) | |