Datasets:
docs: add validated train-from-scratch and LLM-benchmark examples
Browse files
README.md
CHANGED
|
@@ -1877,6 +1877,139 @@ ds = load_dataset(
|
|
| 1877 |
short = ds["train"].filter(lambda x: x["sequence_length"] <= 32)
|
| 1878 |
```
|
| 1879 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1880 |
## Dataset structure
|
| 1881 |
|
| 1882 |
### Data instances
|
|
|
|
| 1877 |
short = ds["train"].filter(lambda x: x["sequence_length"] <= 32)
|
| 1878 |
```
|
| 1879 |
|
| 1880 |
+
## Worked examples
|
| 1881 |
+
|
| 1882 |
+
The dataset supports two consumption modes, and the generator repo's API covers both: **train from scratch** on the published index rows, or **benchmark a pretrained LLM** on rendered prompts whose answers score against these same targets. Both examples below were run as-is; the quoted numbers are their real output.
|
| 1883 |
+
|
| 1884 |
+
### Train from scratch: state tracking with dense supervision
|
| 1885 |
+
|
| 1886 |
+
The composition task is a running-state problem, so supervise the *running product at every prefix*, not just the final target — `permutation_map` lets you compute every prefix label locally. (With final-target supervision alone, small models tend to memorize rows instead of learning the group: an identical setup trained this way sat at chance on held-out rows.)
|
| 1887 |
+
|
| 1888 |
+
<details>
|
| 1889 |
+
<summary><b>Full training script</b> (PyTorch; runs on CPU in ~10 minutes)</summary>
|
| 1890 |
+
|
| 1891 |
+
```python
|
| 1892 |
+
import json
|
| 1893 |
+
import numpy as np
|
| 1894 |
+
import torch
|
| 1895 |
+
import torch.nn as nn
|
| 1896 |
+
from datasets import load_dataset
|
| 1897 |
+
from huggingface_hub import hf_hub_download
|
| 1898 |
+
|
| 1899 |
+
GROUP, MAX_LEN = "c10", 64 # train short, evaluate longer
|
| 1900 |
+
ds = load_dataset("BeeGass/Group-Theory-Collection", name=GROUP)
|
| 1901 |
+
meta = json.load(open(hf_hub_download(
|
| 1902 |
+
"BeeGass/Group-Theory-Collection", f"data/{GROUP}/metadata.json", repo_type="dataset"
|
| 1903 |
+
)))
|
| 1904 |
+
order, degree = meta["group_order"], meta["group_degree"]
|
| 1905 |
+
perms = {int(k): np.array(v) for k, v in meta["permutation_map"].items()}
|
| 1906 |
+
index_of = {tuple(perms[i]): i for i in range(order)}
|
| 1907 |
+
PAD, IGNORE = order, -100
|
| 1908 |
+
|
| 1909 |
+
def encode(row):
|
| 1910 |
+
"""labels[t] = index of p_1 . ... . p_(t+1); labels[-1] == int(row["target"])."""
|
| 1911 |
+
ids = [int(t) for t in row["input_sequence"].split()]
|
| 1912 |
+
state, labels = np.arange(degree), []
|
| 1913 |
+
for i in ids:
|
| 1914 |
+
state = state[perms[i]] # same fold as the decode recipe above
|
| 1915 |
+
labels.append(index_of[tuple(state)])
|
| 1916 |
+
return {"ids": ids, "labels": labels}
|
| 1917 |
+
|
| 1918 |
+
train = ds["train"].filter(lambda r: r["sequence_length"] <= MAX_LEN).map(encode)
|
| 1919 |
+
|
| 1920 |
+
def collate(batch):
|
| 1921 |
+
width = max(len(r["ids"]) for r in batch)
|
| 1922 |
+
x = torch.full((len(batch), width), PAD, dtype=torch.long)
|
| 1923 |
+
y = torch.full((len(batch), width), IGNORE, dtype=torch.long)
|
| 1924 |
+
for i, r in enumerate(batch):
|
| 1925 |
+
x[i, : len(r["ids"])] = torch.tensor(r["ids"])
|
| 1926 |
+
y[i, : len(r["labels"])] = torch.tensor(r["labels"])
|
| 1927 |
+
return x, y
|
| 1928 |
+
|
| 1929 |
+
loader = torch.utils.data.DataLoader(train, batch_size=128, shuffle=True, collate_fn=collate)
|
| 1930 |
+
|
| 1931 |
+
class Composer(nn.Module):
|
| 1932 |
+
"""Recurrent baseline: an RNN can carry the running product in its state.
|
| 1933 |
+
|
| 1934 |
+
Swap this module for your transformer or SSM to probe the TC0/NC1
|
| 1935 |
+
boundary — fixed-depth parallel architectures are the ones predicted to
|
| 1936 |
+
fail at length where this recurrent baseline succeeds.
|
| 1937 |
+
"""
|
| 1938 |
+
|
| 1939 |
+
def __init__(self, order, d=128):
|
| 1940 |
+
super().__init__()
|
| 1941 |
+
self.emb = nn.Embedding(order + 1, d) # + PAD
|
| 1942 |
+
self.rnn = nn.LSTM(d, d, batch_first=True)
|
| 1943 |
+
self.head = nn.Linear(d, order)
|
| 1944 |
+
|
| 1945 |
+
def forward(self, x):
|
| 1946 |
+
hidden, _ = self.rnn(self.emb(x))
|
| 1947 |
+
return self.head(hidden)
|
| 1948 |
+
|
| 1949 |
+
model = Composer(order)
|
| 1950 |
+
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
|
| 1951 |
+
for epoch in range(30):
|
| 1952 |
+
for x, y in loader:
|
| 1953 |
+
logits = model(x)
|
| 1954 |
+
loss = nn.functional.cross_entropy(logits.flatten(0, 1), y.flatten(), ignore_index=IGNORE)
|
| 1955 |
+
opt.zero_grad(); loss.backward(); opt.step()
|
| 1956 |
+
|
| 1957 |
+
@torch.no_grad()
|
| 1958 |
+
def final_accuracy(rows):
|
| 1959 |
+
hits = total = 0
|
| 1960 |
+
for x, y in torch.utils.data.DataLoader(rows, batch_size=256, collate_fn=collate):
|
| 1961 |
+
last = (x != PAD).sum(1) - 1
|
| 1962 |
+
idx = torch.arange(len(x))
|
| 1963 |
+
pred = model(x).argmax(-1)[idx, last]
|
| 1964 |
+
hits += (pred == y[idx, last]).sum().item(); total += len(x)
|
| 1965 |
+
return hits / total
|
| 1966 |
+
|
| 1967 |
+
test = ds["test"].map(encode)
|
| 1968 |
+
in_dist = test.filter(lambda r: r["sequence_length"] <= MAX_LEN)
|
| 1969 |
+
longer = test.filter(lambda r: MAX_LEN < r["sequence_length"] <= 4 * MAX_LEN)
|
| 1970 |
+
print(f"len<={MAX_LEN}: {final_accuracy(in_dist):.3f} | len {MAX_LEN+1}-{4*MAX_LEN}: {final_accuracy(longer):.3f}")
|
| 1971 |
+
```
|
| 1972 |
+
|
| 1973 |
+
</details>
|
| 1974 |
+
|
| 1975 |
+
Measured output of that script, run verbatim (CPU, ~10 min; training loss falls from 2.30, chance level, to below 0.01):
|
| 1976 |
+
|
| 1977 |
+
```
|
| 1978 |
+
len<=64: 1.000 | len 65-256: 0.999
|
| 1979 |
+
```
|
| 1980 |
+
|
| 1981 |
+
The LSTM baseline learns the group and generalizes to 4× its training length, because a recurrent state can implement the group's multiplication directly. The experiment this benchmark exists for: replace `Composer` with a fixed-depth transformer or SSM, sweep `GROUP` across the TC⁰/NC¹ boundary (say `c10`, `d10`, `s5`, `a5`, `m11`), and compare accuracy-versus-length curves per class.
|
| 1982 |
+
|
| 1983 |
+
### Benchmark a pretrained LLM: rendered prompts via the generator API
|
| 1984 |
+
|
| 1985 |
+
The generator package renders these exact composition tasks as natural-language prompts (cycle or one-line notation), parses free-form completions back to element indices, and scores them against the same targets. Task files are self-describing JSONL (each carries its own element table), and `gdg verify` recomputes every target and answer before you spend model calls on a file.
|
| 1986 |
+
|
| 1987 |
+
```python
|
| 1988 |
+
# pip install git+https://github.com/BeeGass/Group-Dataset-Generator
|
| 1989 |
+
from gdg.bench import registry
|
| 1990 |
+
from gdg.bench.generate import generate_tasks
|
| 1991 |
+
from gdg.bench.render import get_renderer
|
| 1992 |
+
|
| 1993 |
+
spec = registry.get("s5")
|
| 1994 |
+
manifest, tasks = generate_tasks(spec, lengths=(4, 16, 64), n=50, seed=0, renderer_name="cycle")
|
| 1995 |
+
renderer = get_renderer(manifest.renderer)
|
| 1996 |
+
|
| 1997 |
+
correct = 0
|
| 1998 |
+
for task in tasks:
|
| 1999 |
+
completion = my_llm(task.prompt) # your model call goes here
|
| 2000 |
+
predicted = renderer.parse_answer(completion, spec, manifest.elements)
|
| 2001 |
+
correct += predicted == task.target # None (unparseable) scores wrong
|
| 2002 |
+
print(f"accuracy: {correct / len(tasks):.3f}")
|
| 2003 |
+
```
|
| 2004 |
+
|
| 2005 |
+
A rendered `cycle` prompt looks like:
|
| 2006 |
+
|
| 2007 |
+
> Compute the product (0 4 3 2) . (0 1)(2 3) . (0 2)(1 3) . (0 3)(2 4) in the group S5, a permutation group on 5 points labelled 0 to 4. Compose so that the rightmost factor acts on a point first. Answer in cycle notation.
|
| 2008 |
+
|
| 2009 |
+
with reference answer `(0 4 1)(2 3)`. `parse_answer` accepts any valid spelling of the same permutation (cycle notation is not unique), returns an element index rather than a string, and returns `None` on junk instead of raising, so one garbled completion cannot abort a sweep. Sanity-checked as-is: an oracle that replays each task's reference answer scores 1.000; a model that answers "banana" scores 0.000.
|
| 2010 |
+
|
| 2011 |
+
The same harness works offline from files: `gdg generate --group s5 --lengths 4,16,64 --n 50 --renderer cycle --out s5.jsonl` writes the tasks (prompts, answers, and the element table) as JSONL, `gdg verify s5.jsonl` proves the file self-consistent, and three renderers ship (`cycle`, `inline` one-line arrays, `index` raw indices — the published corpus format).
|
| 2012 |
+
|
| 2013 |
## Dataset structure
|
| 2014 |
|
| 2015 |
### Data instances
|