File size: 9,182 Bytes
3970207
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# DiscoLoop: Looping Discrete Embeddings and Continuous Hidden States for Multi-hop Reasoning

Code and data for the synthetic multi-hop reasoning experiments of the paper: the symbolic
two-hop task (Section 3, Section 5.1), the symbolic three-hop task (Appendix A.2), the synthetic
natural-language two-hop task (Section 5.2, Appendix A.3), and the analysis of the vanilla looped
transformer in Section 3.2 (Table 1, Figure 2).

DiscoLoop augments the recurrence of a looped transformer with a discrete embedding channel:
after each loop (except the last), the hidden state is decoded through the tied LM head,
re-encoded as the probability-weighted sum of token embeddings, normalized, and added to the
continuous hidden state that is fed to the next loop. The exact update rules are documented at
the top of `train_twin_hyper.py` and `train_twin_hyper_real.py` (the natural-language trainer
also RMS-normalizes the continuous state in every loop).

## Repository layout

| Path | Contents |
|---|---|
| `train_twin_hyper.py`, `train_twin_hyper.sh` | Trainer and launcher for the symbolic tasks: DiscoLoop, the vanilla looped transformer and the non-looped (stacked) baseline |
| `train_twin_hyper_real.py`, `train_twin_hyper_real.sh` | Trainer and launcher for the synthetic natural-language task |
| `scripts/` | One launcher per experiment (see [Experiments](#experiments)) |
| `interp_intervention.py` | Section 3.2 analysis: Stage-1/Stage-2 accuracy, logit lens, training-free intervention |
| `data/`, `multi-hop/data/custom/` | Datasets of the experiments |
| `multi-hop/tokenizers/gpt2_names_relations/` | GPT-2 tokenizer extended with the entity names and relations as added tokens |
| `prepare_data.sh` | Regenerates all datasets and the tokenizer with `data_preparation.py`, `generate_multihop_from_atoms.py` and `multi-hop/*.py` |

## Setup

Python 3.10 and a CUDA GPU:

```bash
pip install torch==2.9.1 --index-url https://download.pytorch.org/whl/cu128
pip install -r requirements.txt
```

- The symbolic trainer, `interp_intervention.py` and `prepare_data.sh` load the GPT-2 tokenizer
  (`gpt2`) from the Hugging Face Hub on first use; afterwards `HF_HUB_OFFLINE=1` works. The
  natural-language trainer only uses the shipped tokenizer. If your environment sets
  `HF_HUB_ENABLE_HF_TRANSFER=1`, install `hf_transfer` or unset the variable for the download.
- `wandb` is optional and only used when a run is started with `--wandb-project NAME`.

## Data

All datasets are included in the repository. `bash prepare_data.sh` regenerates every dataset and
the natural-language tokenizer from scratch, rewriting the shipped files in place with
byte-identical content.

| Dataset | Directory | Used in |
|---|---|---|
| Symbolic two-hop | `data/twin_twohop_truood_diff.500.50.10` | Sec. 3, Sec. 5.1 |
| Symbolic two-hop + three-hop | `data/twin_23hop_truood_diff.500.50.10` | App. A.2 |
| Natural language, direct format | `multi-hop/data/custom/two_graph_direct` | Sec. 5.2, App. A.3 |
| Natural language, reverse format | `multi-hop/data/custom/two_graph_reverse` | Sec. 5.2, App. A.3 |

- **Symbolic two-hop.** Two entity-disjoint graphs with 500 entities each, 50 shared relations
  and out-degree 10. `train.json` holds all 10,000 atomic facts of both graphs and all 50,000
  two-hop chains of the in-distribution graph; `test.json` holds the 50,000 two-hop chains of the
  out-of-distribution graph. The trainer samples 10,000 chains for training
  (`--train-twohop-count`), 2,000 of the remaining chains as the ID test set and 2,000 OOD chains
  (`--eval-id-count`, `--eval-ood-count`).
- **Symbolic three-hop.** Built from the same atomic facts: 10,000 atomic facts, 5,000 two-hop and
  5,000 three-hop chains for training. `test_id.json` / `test_ood.json` hold 2,000 chains per hop
  count, of which 1,000 are sampled for evaluation.
- **Natural language.** 200 entities per graph and 50 relations; atomic facts read like
  `Charlie's chancellor is Julius`. Training: 3,981 atomic facts and 2,000 two-hop questions;
  1,000 ID and 1,000 OOD test questions. The direct and reverse datasets share the same facts and
  chains and differ only in the question format (`Finley's foreman's president is Anya` vs.
  `Who is the president of the foreman of Finley?\nAnswer: Anya`).

## Experiments

Run the commands from the repository root. Each command trains one model; `<model>` is one of
`discoloop`, `vanilla` and `noloop`, and `<format>` one of `direct` and `reverse`.

| Paper | Command |
|---|---|
| Table 1a, Fig. 1, Fig. 3: symbolic two-hop (K=2, 3000 epochs) | `bash scripts/symbolic_2hop.sh <model> --gpu 0` |
| Fig. 5: symbolic three-hop (K=3, 5000 epochs) | `bash scripts/symbolic_3hop.sh <model> --gpu 0` |
| Fig. 4, Fig. 6: natural language (K=2, 5000 epochs) | `bash scripts/nl_2hop.sh <format> <model> --gpus 0,1` |
| Table 1, Fig. 2: analysis of the vanilla looped model | `python interp_intervention.py --run-dir <output dir of scripts/symbolic_2hop.sh vanilla> --device cuda:0` |

Each script fixes the data, model and schedule of its experiment and forwards any further option
to its launcher (`./train_twin_hyper.sh --help`, `./train_twin_hyper_real.sh --help`), e.g.
`--gpu`/`--gpus` to choose devices, `--out DIR` for the output directory (default:
`outputs/...`) and `--seed S`. The seed sets the model initialization and the sampled
train/test split; data order and dropout follow the fixed seed of the Hugging Face Trainer.

Models:

- `discoloop`: DiscoLoop. The symbolic tasks use a fixed gate (`--gate-mode fixed --fixed-alpha 1
  --fixed-beta 0`); the natural-language task uses the learned gate (`--gate-mode learned`).
- `vanilla`: the looped transformer without the discrete channel.
- `noloop`: the non-looped baseline that stacks K untied copies of the blocks
  (`--design stacking`). The base GPT-2 is first trained for `--stage1-epochs` epochs (50 for the
  symbolic tasks, 10 for the natural-language task), and the K copies of its blocks start from
  these weights; with `--skip-stage1` they are copies of the random initialization.

The base model is a GPT-2 decoder trained from scratch (2 layers, 16 heads, hidden size 1280,
dropout 0.1, tied input/output embeddings), optimized with AdamW (learning rate 1e-3, weight
decay 0.01, 200 warmup steps, cosine schedule, gradient clipping at norm 1.0) with the loss on
the answer only. Symbolic runs use one GPU and a batch size of 2048. Natural-language runs use
two GPUs with 512 sequences each (`--batch-size` is per GPU in `train_twin_hyper_real.sh`); under
`torchrun` the Hugging Face Trainer scales the loss of this model by the number of processes, so
runs with a different number of GPUs are not equivalent.

### Outputs

Each run writes to `<out>/stage2_hyper/`:

- `log_epochs.json`: accuracy on every evaluation split every 10 epochs (`--evaluate-epoch`),
  also sent to W&B when `--wandb-project` is set;
- `final_metrics.json`: the same metrics at the end of training;
- `hyper_model.pt`: model weights and configuration (read by `interp_intervention.py`);
- the tokenizer files and the last Hugging Face Trainer checkpoints (`checkpoint-*`, every 500
  steps). Stacked runs also write the stage-1 model to `<out>/stage1_gpt/`.

`<split>_stage<k>_acc` is the accuracy of the answer predicted by the LM head from the hidden
state after loop k (for DiscoLoop, after the discrete channel has been added), and
`<split>_final_acc` the accuracy after the last loop. The evaluation splits are

- symbolic tasks: `train_atom`, `train_2hop` (and `train_3hop`), `test_2hop_id`, `test_2hop_ood`
  (and `test_3hop_id`, `test_3hop_ood`);
- natural language: `train_atom`, `train_multihop`, `test_id`, `test_ood`.

The ID/OOD curves of Fig. 3-5 are `test_*_final_acc`. The Stage-1 two-hop training accuracy
(Fig. 3 right, Fig. 6) is `train_2hop_stage1_acc` (symbolic) or `train_multihop_stage1_acc`
(natural language) for the looped models, and the final training accuracy
(`train_2hop_final_acc` / `train_multihop_final_acc`) for the non-looped baseline.

### Section 3.2 analysis

`interp_intervention.py` loads a vanilla looped model (K=2) trained with
`scripts/symbolic_2hop.sh vanilla`, rebuilds the run's train/test split, and writes
`<run dir>/interp_section3.json` (or `--out FILE`) with

- `baseline`: Stage-1 and Stage-2 accuracy on `train_atom`, `train_2hop` (the two-hop training
  chains), `test_id` and `test_ood` (Table 1a);
- `logit_lens`: the probability of the bridge entity and the cosine similarity between the
  hidden state and the bridge embedding at position 1 after the first loop (Table 1b);
- `intervention`: ID and OOD accuracy of the training-free intervention of Eq. 3 for a sweep of
  alpha (Fig. 2).

Run it from the repository root (runs store the dataset path relative to it), or pass
`--data-dir`.

## Not included

The language-model pretraining experiments of Section 5.3 and Appendix B are not part of this
repository.

## Acknowledgements

The symbolic data generator is adapted from the code of Ye et al. (2025), *How do transformers
learn implicit reasoning?* The natural-language tokenizer extends the GPT-2 tokenizer (OpenAI,
MIT license).