# looped-gpt A small experiment that turns pretrained **DistilGPT2** into a looped Transformer and fine-tunes it with plain PyTorch. No `Trainer`, Accelerate, TRL, LoRA, or distributed training. Transformers supplies the tokenizer, pretrained blocks, and `save_pretrained` / `from_pretrained` / `generate` integration. [DistilGPT2](https://huggingface.co/distilbert/distilgpt2) has six blocks and about 82M parameters. It is smaller than the original 12-block [OpenAI GPT](https://huggingface.co/openai-community/openai-gpt). This example supports GPT-2-family checkpoints; OpenAI GPT uses a different architecture. ## What gets looped? The default repeats blocks 2 and 3 three times, with zero-based indices: ```text dense: embeddings → 0 → 1 → [2 → 3] → 4 → 5 → head looped: embeddings → 0 → 1 → [2 → 3] → [2 → 3] → [2 → 3] → 4 → 5 → head ``` All three appearances of block 2 refer to **one module**, and likewise for block 3. Hidden states flow between passes without detaching. Autograd adds the gradients from every use of the shared weights. All parameters are trained. There are still six unique blocks and the same parameter count; looping adds computation (ten block executions), not parameters or context length. `--num-loops 1` gives exactly the dense forward pass. The important part of [model.py](model.py) is: ```python for index in self.layer_order(num_loops): hidden = self.transformer.h[index]( hidden, attention_mask=mask, use_cache=False )[0] ``` KV caching is disabled because each execution of a shared block would need separate cache state. For this short, one-token-answer task, recomputing the context keeps the implementation simple and correct. This is an instructional GPT-2 forward, not a complete replacement for all Transformers model features. It accepts token IDs, attention/position masks, labels, and loop overrides. ## The reasoning task Follow a shuffled table of directed edges: ```text D>E B>C H>A F>G A>B G>H C>D E>F Start: A. Steps: 3. Answer: ``` The target is ` D`: A → B → C → D. Each graph is a cycle through eight nodes, so the answer always requires the requested number of transitions. There are 5,040 possible graphs. No graph is shared between train, validation, and test. The table order is randomized, and the model receives only the prompt and final-answer supervision, never the oracle path saved in the dataset. | Split | Examples | Path length | Purpose | |---|---:|---:|---| | train | 12,000 | 1–3 | Fine-tuning | | validation | 512 | 1–3 | Progress monitoring | | test | 512 | 1–3 | Unseen-graph accuracy | | test_long | 512 | 4–6 | Longer-path generalization | `test_long` draws from the same held-out graph pool as `test`. Data is generated deterministically by [data.py](data.py), with no dataset download. Labels mask the prompt and padding with `-100`; causal cross-entropy trains only the answer. Evaluation takes the highest-probability next token over the **full vocabulary**, without showing the target or restricting outputs to A–H. Uniform guessing among the eight nodes scores 12.5%. This is a small algorithmic reasoning probe. Improved task accuracy is not proof of general reasoning, and looping is not guaranteed to improve it. The default experiment compares independent fine-tunes from the same pretrained checkpoint, using identical data, seed, batches, optimizer steps, and hyperparameters. It records before/after accuracy and results by hop count. It also evaluates each trained checkpoint with 1, 2, 3, and 4 internal loops. That sweep tests sensitivity to inference computation, including counts not used during training. The dense and looped runs are parameter- and data-matched, **not compute-matched**. A stronger study would add multiple seeds and a dense baseline with an equal compute budget. Final test scores do not select checkpoints or hyperparameters. ## Run locally Use Python 3.11–3.13; the tested environment is Python 3.12. ```bash uv venv --python 3.12 uv pip install -r requirements.txt # Default: both variants, 1,000 optimizer steps each. .venv/bin/python train.py --device cuda # Short plumbing check with random, tiny weights; not a reasoning result. .venv/bin/python train.py --tiny --device cpu --steps 2 \ --train-size 16 --eval-size 8 --batch-size 4 \ --eval-every 1 --save-every 1 --output-dir outputs-smoke # Publish models and data under your own namespace. .venv/bin/python train.py --device cuda --hub-prefix YOUR_NAME/looped-distilgpt2 ``` Without `--hub-prefix`, everything stays local. `--private` creates private Hub repos. Use a fresh `--output-dir` for each run. CUDA uses BF16 when supported; other devices use FP32. Automatic device selection prefers CUDA, then MPS, then CPU. CPU/MPS are useful for smoke tests; a GPU is recommended for the full run. Read [train.py](train.py) for the complete loop: load a batch, compute masked loss, call `backward()`, clip gradients, and call `AdamW.step()`. The remaining code evaluates and exports the run. `--help` lists all settings. ## Run on Hugging Face Jobs Authenticate with `hf auth login`. Upload the exact source you want the job to run; the allowlist excludes credentials, caches, and local outputs: ```bash hf upload YOUR_NAME/looped-distilgpt2-data . source --type dataset \ --include model.py --include data.py --include train.py \ --include run_job.py --include requirements.txt --include README.md \ --include 'tests/*.py' hf datasets info YOUR_NAME/looped-distilgpt2-data --expand sha --format json # Replace SOURCE_COMMIT with the immutable SHA returned above. hf jobs uv run --flavor l4x1 --timeout 30m --detach \ --secrets HF_TOKEN --env PYTHONUNBUFFERED=1 \ --env TOKENIZERS_PARALLELISM=false --python 3.12 \ -- run_job.py --source-repo YOUR_NAME/looped-distilgpt2-data \ --source-revision SOURCE_COMMIT \ --base-revision 2290a62682d06624634c1f46a6ad5be0f47f38aa \ --device cuda --hub-prefix YOUR_NAME/looped-distilgpt2 hf jobs logs JOB_ID --follow hf jobs inspect JOB_ID ``` The job entrypoint downloads the pinned source snapshot, installs the pinned dependencies, and runs the same training script. `--secrets HF_TOKEN` forwards your saved credential without putting its value in the command. Source and base model revisions are recorded in the metrics. Hardware prices can be checked with `hf jobs hardware`; the [Jobs documentation](https://huggingface.co/docs/hub/jobs-pricing) explains billing and timeout limits. ## Artifacts and loading Each run writes: ```text outputs/ data/{train,validation,test,test_long}.jsonl dense/ and looped/ model.safetensors, config.json, generation_config.json, model.py tokenizer files, README.md, metrics.json, history.jsonl predictions_test.json, predictions_test_long.json, source/ comparison.json ``` With `--hub-prefix USER/NAME`, models are uploaded to `USER/NAME-dense` and `USER/NAME-looped`; data, source, and the comparison go to `USER/NAME-data`. Weights and logs are uploaded every 200 steps and at completion, so artifacts survive the ephemeral job. A timed-out run can have partial checkpoints: inspect `metrics.json` for `status`, `step`, and the expected total. Optimizer state is not saved, so these are inference checkpoints, not exact training-resume files. ```python from transformers import AutoModelForCausalLM, AutoTokenizer repo = "outputs/looped" # or "YOUR_NAME/looped-distilgpt2-looped" 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") output = model.generate(**inputs, max_new_tokens=1, do_sample=False, use_cache=False) print(tokenizer.decode(output[0, inputs.input_ids.shape[1]:])) # Change internal depth without changing the checkpoint's weights. logits = model(**inputs, num_loops=4).logits[:, -1] ``` Inspect `model.py` before enabling `trust_remote_code`; it is needed for the custom model class. Use the pinned requirements, since this small implementation calls Transformers' GPT-2 blocks directly. The answer shown above is a target, not a promised model prediction. ## Checks ```bash uv pip install pytest==8.4.2 .venv/bin/python -m pytest -q ``` Tests run without network access on tiny random models. They check one-loop equivalence to dense GPT-2, shared-gradient accumulation against independently unrolled copies, causal and padding masks, answer-only loss, graph separation, and a real `AutoModelForCausalLM` save/reload/generate round trip.