ariG23498's picture
ariG23498 HF Staff
Plain PyTorch looped GPT-2 experiment and tests
1d0b885 verified
Raw History Blame Contribute Delete
16.4 kB
"""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()