Datasets:
File size: 16,359 Bytes
1d0b885 | 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 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 | """Plain PyTorch fine-tuning: DataLoader -> forward -> backward -> AdamW."""
import argparse
from contextlib import nullcontext
from functools import partial
import json
import math
import os
from pathlib import Path
import random
import shutil
import time
from huggingface_hub import HfApi
import torch
from torch.utils.data import DataLoader
import transformers
from transformers import AutoTokenizer, GPT2Config, GPT2LMHeadModel
from data import AnswerDataset, collate, make_data, save_data
from model import LoopedGPT2LMHeadModel
def write_json(path, value):
Path(path).write_text(json.dumps(value, indent=2) + "\n")
def autocast(device):
# FP32 on CPU/MPS; BF16 on supported CUDA GPUs, otherwise FP32 (no scaler).
if device.type == "cuda" and torch.cuda.is_bf16_supported():
return torch.autocast("cuda", dtype=torch.bfloat16)
return nullcontext()
@torch.no_grad()
def evaluate(model, tokenizer, records, device, batch_size, num_loops=None):
model.eval()
predictions, groups = [], {}
for start in range(0, len(records), batch_size):
rows = records[start:start + batch_size]
# Left padding makes the final position the end of every prompt.
tokens = tokenizer([row["prompt"] for row in rows], padding=True,
return_tensors="pt").to(device)
with autocast(device):
logits = model(**tokens, num_loops=num_loops, logits_to_keep=1).logits[:, -1]
predicted = tokenizer.batch_decode(logits.argmax(-1), skip_special_tokens=True)
for row, answer in zip(rows, predicted):
correct = answer.strip() == row["answer"].strip()
group = groups.setdefault(str(row["hops"]), {"correct": 0, "count": 0})
group["correct"] += int(correct)
group["count"] += 1
predictions.append(dict(**row, prediction=answer, correct=correct))
correct = sum(group["correct"] for group in groups.values())
for group in groups.values():
group["accuracy"] = group["correct"] / group["count"]
return {"accuracy": correct / len(records), "correct": correct,
"count": len(records), "by_hops": groups}, predictions
def model_card(args, metrics, repo_id):
dataset_metadata = f"datasets:\n- {args.hub_prefix}-data\n" if args.hub_prefix else ""
return f"""---
library_name: transformers
license: apache-2.0
base_model: {args.base_model}
{dataset_metadata}tags:
- looped-transformer
- pytorch
- custom_code
pipeline_tag: text-generation
---
# {repo_id.rsplit('/', 1)[-1]}
DistilGPT2 fine-tuned on synthetic pointer chasing with a plain PyTorch loop.
The middle blocks [{args.loop_start}, {args.loop_end}) execute
{metrics['num_loops']} time(s); all other blocks execute once. Weights are shared
across iterations, and all parameters are trained. No KV cache is used.
Status: **{metrics['status']}**, step {metrics['step']} / {args.steps}.
See `metrics.json` for exact-match accuracy by path length, `history.jsonl` for
training progress, and `source/` for the complete recipe. The checkpoint has
{metrics['parameters']:,} unique parameters and executes
{metrics['effective_depth']} blocks per forward pass.
```python
from transformers import AutoModelForCausalLM, AutoTokenizer
repo = "{repo_id}"
tokenizer = AutoTokenizer.from_pretrained(repo, padding_side="left")
model = AutoModelForCausalLM.from_pretrained(repo, trust_remote_code=True).eval()
prompt = "A>B B>C C>D D>E E>F F>G G>H H>A\\nStart: A. Steps: 3. Answer:"
inputs = tokenizer(prompt, return_tensors="pt")
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=1,
do_sample=False, use_cache=False)[0, inputs.input_ids.shape[1]:]))
```
Install the pinned `source/requirements.txt`. Inspect `model.py` before allowing
custom model code. Generation is ordinary autoregressive decoding without a KV
cache; this benchmark scores one unconstrained answer token from the full
vocabulary. There are eight possible answers (uniform guessing: 12.5%).
Train/validation/test graphs are disjoint. Training uses 1–3 hops; `test_long`
uses 4–6 hops. Longer paths are a harder generalization check. This is a toy
algorithmic task, not evidence of general reasoning. A single seed and more
compute in the looped variant do not establish a causal benefit from looping.
Check the dense baseline and inference-loop ablations before drawing conclusions.
Checkpoints contain inference weights, not optimizer state for exact resumption.
"""
def save_checkpoint(model, tokenizer, directory, metrics, args, repo_id):
model.save_pretrained(directory, safe_serialization=True)
tokenizer.save_pretrained(directory)
write_json(directory / "metrics.json", metrics)
(directory / "README.md").write_text(model_card(args, metrics, repo_id))
source = directory / "source"
source.mkdir(exist_ok=True)
for filename in ("model.py", "data.py", "train.py", "run_job.py", "requirements.txt"):
shutil.copy2(Path(__file__).parent / filename, source / filename)
if args.hub_prefix:
api = HfApi()
api.create_repo(repo_id, exist_ok=True, private=args.private)
api.upload_folder(repo_id=repo_id, folder_path=directory,
commit_message=f"{metrics['status']} at step {metrics['step']}")
def train_one(args, splits, tokenizer, device, variant):
random.seed(args.seed)
torch.manual_seed(args.seed)
if device.type == "cuda":
torch.cuda.manual_seed_all(args.seed)
loops = 1 if variant == "dense" else args.num_loops
if args.tiny:
dense = GPT2LMHeadModel(GPT2Config(
vocab_size=len(tokenizer), n_embd=32, n_head=2, n_layer=6,
n_positions=128, bos_token_id=tokenizer.bos_token_id,
eos_token_id=tokenizer.eos_token_id,
))
else:
dense = GPT2LMHeadModel.from_pretrained(args.base_model,
revision=args.base_revision, attn_implementation="sdpa")
resolved_revision = getattr(dense.config, "_commit_hash", None)
model = LoopedGPT2LMHeadModel.from_dense(
dense, loop_start=args.loop_start, loop_end=args.loop_end, num_loops=loops)
del dense
model.config.pad_token_id = tokenizer.pad_token_id
model.generation_config.pad_token_id = tokenizer.pad_token_id
model.to(device)
directory = Path(args.output_dir) / variant
directory.mkdir(parents=True, exist_ok=True)
repo_id = f"{args.hub_prefix}-{variant}" if args.hub_prefix else variant
metrics = dict(variant=variant, num_loops=loops, status="training", step=0,
parameters=sum(p.numel() for p in model.parameters()),
effective_depth=len(model.layer_order()), args=vars(args),
base_revision=resolved_revision, torch=torch.__version__,
transformers=transformers.__version__, device=str(device),
gpu=torch.cuda.get_device_name() if device.type == "cuda" else None,
job_id=os.environ.get("JOB_ID"), source_revision=os.environ.get("SOURCE_REVISION"))
metrics["before"] = {
name: evaluate(model, tokenizer, splits[name], device, args.batch_size)[0]
for name in ("test", "test_long")
}
print(json.dumps({"variant": variant, "before": metrics["before"]}), flush=True)
dataset = AnswerDataset(splits["train"], tokenizer)
if max(len(ids) for ids, _ in dataset.examples) > model.config.n_positions:
raise ValueError("Training examples exceed model context length")
loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=True,
generator=torch.Generator().manual_seed(args.seed),
collate_fn=partial(collate, pad_token_id=tokenizer.pad_token_id))
optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=0.01)
batches = iter(loader)
started = time.monotonic()
if device.type == "cuda":
torch.cuda.reset_peak_memory_stats()
with (directory / "history.jsonl").open("w") as history:
for step in range(1, args.steps + 1):
try:
batch = next(batches)
except StopIteration:
batches = iter(loader)
batch = next(batches)
batch = {key: value.to(device) for key, value in batch.items()}
warmup = min(50, max(1, args.steps // 10))
progress = max(0, step - warmup) / max(1, args.steps - warmup)
scale = min(step / warmup, 1) * (0.1 + 0.9 * (1 + math.cos(math.pi * progress)) / 2)
for group in optimizer.param_groups:
group["lr"] = args.lr * scale
# The complete optimization loop: no Trainer, Accelerate, or TRL.
model.train()
optimizer.zero_grad(set_to_none=True)
with autocast(device):
loss = model(**batch).loss
if not torch.isfinite(loss):
raise RuntimeError(f"Nonfinite loss at step {step}")
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0, error_if_nonfinite=True)
optimizer.step()
event = dict(step=step, loss=loss.item(), lr=args.lr * scale,
elapsed_seconds=time.monotonic() - started)
if step % args.eval_every == 0 or step == args.steps:
event["validation"] = evaluate(model, tokenizer, splits["validation"],
device, args.batch_size)[0]
history.write(json.dumps(event) + "\n")
history.flush()
if step == 1 or step % 50 == 0 or "validation" in event:
print(json.dumps(dict(variant=variant, **event)), flush=True)
metrics["step"] = step
if step % args.save_every == 0 and step != args.steps:
save_checkpoint(model, tokenizer, directory, metrics, args, repo_id)
metrics["training_seconds"] = time.monotonic() - started
metrics["peak_cuda_memory_bytes"] = (torch.cuda.max_memory_allocated()
if device.type == "cuda" else None)
metrics["after"], metrics["loop_sweep"] = {}, {}
for name in ("test", "test_long"):
result, predictions = evaluate(model, tokenizer, splits[name], device, args.batch_size)
metrics["after"][name] = result
write_json(directory / f"predictions_{name}.json", predictions)
# Same trained weights, changing only the number of internal iterations.
for count in sorted({1, 2, args.num_loops, args.num_loops + 1}):
metrics["loop_sweep"][str(count)] = {
name: evaluate(model, tokenizer, splits[name], device, args.batch_size, count)[0]
for name in ("test", "test_long")
}
metrics["status"] = "complete"
save_checkpoint(model, tokenizer, directory, metrics, args, repo_id)
print(json.dumps({"variant": variant, "after": metrics["after"]}), flush=True)
del model, optimizer
if device.type == "cuda":
torch.cuda.empty_cache()
return metrics
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-model", default="distilbert/distilgpt2")
parser.add_argument("--base-revision", default="main")
parser.add_argument("--variant", choices=["dense", "looped", "both"], default="both")
parser.add_argument("--loop-start", type=int, default=2)
parser.add_argument("--loop-end", type=int, default=4)
parser.add_argument("--num-loops", type=int, default=3)
parser.add_argument("--steps", type=int, default=1000)
parser.add_argument("--batch-size", type=int, default=32)
parser.add_argument("--lr", type=float, default=2e-4)
parser.add_argument("--train-size", type=int, default=12000)
parser.add_argument("--eval-size", type=int, default=512)
parser.add_argument("--eval-every", type=int, default=200)
parser.add_argument("--save-every", type=int, default=200)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--device", default="auto", choices=["auto", "cpu", "mps", "cuda"])
parser.add_argument("--output-dir", default="outputs")
parser.add_argument("--hub-prefix", help="e.g. username/looped-distilgpt2; uploads if set")
parser.add_argument("--private", action="store_true", help="Create private Hub repos")
parser.add_argument("--tiny", action="store_true", help="Random tiny model for smoke tests only")
args = parser.parse_args()
for name in ("steps", "batch_size", "train_size", "eval_size", "eval_every", "save_every", "num_loops"):
if getattr(args, name) < 1:
parser.error(f"--{name.replace('_', '-')} must be positive")
if args.lr <= 0 or not math.isfinite(args.lr):
parser.error("--lr must be finite and positive")
if args.hub_prefix and args.tiny:
parser.error("Do not publish random smoke-test checkpoints as trained models")
if args.hub_prefix and "/" not in args.hub_prefix:
parser.error("--hub-prefix must include your namespace")
return args
def main():
args = parse_args()
if args.device == "auto":
args.device = ("cuda" if torch.cuda.is_available() else
"mps" if torch.backends.mps.is_available() else "cpu")
device = torch.device(args.device)
torch.set_num_threads(min(8, os.cpu_count() or 1))
output = Path(args.output_dir)
output.mkdir(parents=True, exist_ok=True)
if any((output / name / "metrics.json").exists() for name in ("dense", "looped")):
raise FileExistsError("Choose a fresh --output-dir; existing runs are not overwritten")
tokenizer = AutoTokenizer.from_pretrained(args.base_model, revision=args.base_revision,
padding_side="left")
tokenizer.pad_token = tokenizer.eos_token
splits = make_data(args.train_size, args.eval_size, args.seed)
save_data(splits, output / "data")
if args.hub_prefix:
api = HfApi()
repo = args.hub_prefix + "-data"
api.create_repo(repo, repo_type="dataset", exist_ok=True, private=args.private)
card = """---
license: apache-2.0
task_categories:
- text-generation
language:
- en
size_categories:
- 10K<n<100K
configs:
- config_name: default
data_files:
- split: train
path: data/train.jsonl
- split: validation
path: data/validation.jsonl
- split: test
path: data/test.jsonl
- split: test_long
path: data/test_long.jsonl
---
# Eight-node pointer chasing
Procedurally generated directed cycles through nodes A–H. Follow the table
from `Start` for `Steps` transitions and output the final node. Each answer is
one GPT-2 token. Tables are shuffled so their display order does not reveal
the path. `path` is an oracle annotation; it is never provided to the model.
Train, validation and test graph sets are disjoint, assigned by SHA256 of the
canonical successor table. Training and the ordinary evaluation splits use
1–3 steps; test_long uses 4–6. Test and test_long draw from the same held-out
graph pool. There are no repeated (graph, start, steps) within a split.
See source/data.py for generation, model repos for weights, and comparison.json
for before/after accuracy and inference-loop ablations when training finishes.
This is a toy algorithmic benchmark, not a general reasoning evaluation.
"""
api.upload_file(repo_id=repo, repo_type="dataset", path_or_fileobj=card.encode(),
path_in_repo="README.md", commit_message="Document synthetic dataset")
api.upload_folder(repo_id=repo, repo_type="dataset", folder_path=output / "data",
path_in_repo="data", commit_message="Deterministic graph-disjoint splits")
variants = ["dense", "looped"] if args.variant == "both" else [args.variant]
results = {name: train_one(args, splits, tokenizer, device, name) for name in variants}
write_json(output / "comparison.json", results)
if args.hub_prefix:
HfApi().upload_file(repo_id=args.hub_prefix + "-data", repo_type="dataset",
path_or_fileobj=output / "comparison.json", path_in_repo="comparison.json")
print(json.dumps({name: result["after"] for name, result in results.items()}, indent=2))
if __name__ == "__main__":
main()
|