Download code/data.py from BigRatz/looped-decision-models: direct link, hf CLI and curl.
- Browser
- Download file 4.25 kB
-
https://huggingface.co/BigRatz/looped-decision-models/resolve/main/code/data.py
- Command line
-
hf download hf://BigRatz/looped-decision-models/code/data.py
-
curl -L -o data.py https://huggingface.co/BigRatz/looped-decision-models/resolve/main/code/data.py
4.25 kB
| """Task: k-hop composition over a random permutation, as a typed decision. | |
| The model reads a shuffled permutation table (u, f(u)) as token pairs, then a | |
| start node and k hop markers. It must return f^k(start) as a distribution over | |
| the N node tokens, in one forward pass, with no generated tokens. | |
| Contamination is impossible by construction: items are generated from a seed and | |
| the test seed is disjoint from train and validation. | |
| """ | |
| from __future__ import annotations | |
| import numpy as np | |
| import torch | |
| class TaskSpec: | |
| def __init__(self, n_nodes: int = 32, k_train: int = 6, k_max: int = 24): | |
| self.n_nodes = n_nodes | |
| self.k_train = k_train | |
| self.bos = n_nodes | |
| self.sep = n_nodes + 1 | |
| self.hop = n_nodes + 2 | |
| self.vocab = n_nodes + 3 | |
| # fixed length for every split, so train and test see the same shape | |
| self.max_len = 1 + 2 * n_nodes + 3 + k_max | |
| def encode(self, perm: np.ndarray, start: int, k: int, | |
| order: np.ndarray | None = None) -> list[int]: | |
| toks = [self.bos] | |
| for u in (order if order is not None else range(self.n_nodes)): | |
| toks.append(int(u)) | |
| toks.append(int(perm[u])) | |
| toks.append(self.sep) | |
| toks.append(int(start)) | |
| toks.append(self.sep) | |
| toks.extend([self.hop] * k) | |
| return toks | |
| def answer(self, perm: np.ndarray, start: int, k: int) -> int: | |
| x = int(start) | |
| for _ in range(k): | |
| x = int(perm[x]) | |
| return x | |
| def make_split(spec: TaskSpec, n: int, seed: int, k_lo: int, k_hi: int): | |
| """Deterministic split. The permutation order is shuffled so that position | |
| carries no information; lookups must be content-based for every model.""" | |
| if k_hi > spec.n_nodes - 2: | |
| # The shown table must hold the k+1 chain nodes plus at least one more | |
| # edge (so the answer is never the unique non-key value). That needs | |
| # k+2 <= n_nodes; anything above crashes inside rng.integers with an | |
| # opaque "low >= high". | |
| raise ValueError( | |
| f"k_hi={k_hi} too large for n_nodes={spec.n_nodes}: " | |
| f"the generator accepts k <= {spec.n_nodes - 2}") | |
| rng = np.random.default_rng(seed) | |
| xs, ks, ys = [], [], [] | |
| for _ in range(n): | |
| perm = rng.permutation(spec.n_nodes) | |
| start = int(rng.integers(spec.n_nodes)) | |
| k = int(rng.integers(k_lo, k_hi + 1)) | |
| # Show only a subset of the table, always including the k edges the chain | |
| # needs. A full permutation gives every item the same token multiset, so a | |
| # uniform-attention model sees identical inputs and the batch gradient | |
| # cancels; subsampling breaks that symmetry without changing the answer. | |
| # k+1 nodes: the last is f^k(start), and showing its out-edge means the | |
| # answer is never the unique "value that is not a key". Without this, a | |
| # partial table is solvable by set difference and k=6 scores above k=1. | |
| chain, cur = [], start | |
| for _ in range(k + 1): | |
| chain.append(cur) | |
| cur = int(perm[cur]) | |
| chain = list(dict.fromkeys(chain)) | |
| need = max(k + 1, 1) | |
| m_show = int(rng.integers(need + 1, spec.n_nodes + 1)) | |
| rest = [u for u in rng.permutation(spec.n_nodes) if u not in set(chain)] | |
| show = chain + rest[: max(0, m_show - need)] | |
| order = rng.permutation(np.array(show, dtype=np.int64)) | |
| xs.append(spec.encode(perm, start, k, order)) | |
| ks.append(k) | |
| ys.append(spec.answer(perm, start, k)) | |
| L = spec.max_len | |
| ids = np.full((n, L), spec.sep, dtype=np.int64) # pad with a neutral token | |
| lens = np.zeros(n, dtype=np.int64) | |
| for i, x in enumerate(xs): | |
| ids[i, : len(x)] = x | |
| lens[i] = len(x) | |
| return { | |
| "ids": torch.from_numpy(ids), | |
| "len": torch.from_numpy(lens), | |
| "k": torch.tensor(ks, dtype=torch.long), | |
| "y": torch.tensor(ys, dtype=torch.long), | |
| } | |
| def describe(spec: TaskSpec, batch: dict) -> str: | |
| return ( | |
| f"N={spec.n_nodes} vocab={spec.vocab} len={batch['ids'].shape[1]} " | |
| f"k={batch['k'].min().item()}..{batch['k'].max().item()} " | |
| f"chance={1.0 / spec.n_nodes:.3f}" | |
| ) | |