Atharva1232 commited on
Commit
4a6c57b
·
verified ·
1 Parent(s): 458f907

1M-param 4-digit addition model + full results (phase diagram, extrapolation, bake-off)

Browse files
Files changed (10) hide show
  1. .gitattributes +1 -0
  2. README.md +135 -0
  3. bakeoff_results.jsonl +6 -0
  4. best.pt +3 -0
  5. curve.csv +12 -0
  6. extrapolation.jsonl +18 -0
  7. phase_diagram.png +3 -0
  8. summary.json +15 -0
  9. sweep_results.jsonl +11 -0
  10. train.py +321 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ phase_diagram.png filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # tiny-math-1m: a 1M-parameter transformer that adds 4-digit numbers
2
+
3
+ **The smallest model in this repo (1,065,088 parameters) solves 4-digit addition
4
+ perfectly — 5000/5000 held-out problems, zero errors — given ~1.8M practice
5
+ problems. It has a 16-token vocabulary (digits 0-9, `+`, `=`, newline, comma,
6
+ pad) and was trained from random initialization. No pretraining, no
7
+ demonstrations, no RL. Plain next-token prediction.**
8
+
9
+ ## The finding this repo exists to report
10
+
11
+ Three model sizes (1M / 5M / 8M) × three data scales (71k / 357k / 1.78M
12
+ practice problems), one task (4-digit addition, chain-of-thought digit steps),
13
+ exact-match on held-out problems:
14
+
15
+ | model | 71k probs | 357k probs | 1.78M probs |
16
+ |---|---|---|---|
17
+ | **1M** | 0.0% | 0.2% | **100.0%** |
18
+ | 5M | 0.0% | 95.7% | 100.0% |
19
+ | 8M | 0.0% | 98.8% | 100.0% |
20
+
21
+ Two things stand out:
22
+
23
+ 1. **The transition is a cliff, not a ramp.** The 1M model sits at 0.2% with
24
+ 357k problems and hits 100.0% with 1.78M. No gradual climb — consistent
25
+ with the sharp data-scale phase transitions reported in *Teaching Arithmetic
26
+ to Small Transformers* (arXiv:2307.03381).
27
+ 2. **Bigger models need less practice.** 5M and 8M cross their thresholds by
28
+ 357k problems; 1M needs ~5× more data. Capacity buys sample efficiency.
29
+
30
+ ## What it learned (and what it didn't)
31
+
32
+ The model writes step-by-step carry chains, e.g. for `1842+2957`:
33
+ `2+7=9,4+5=9,8+9=17,1+2+1=4,4799` — carries computed correctly, digits
34
+ aligned right-to-left. The procedure is real.
35
+
36
+ **But it did not learn the addition algorithm.** Quizzed on digit lengths it
37
+ never trained on (n≈2000 per row, greedy, same format):
38
+
39
+ | tested on | 1M | 5M | 8M |
40
+ |---|---|---|---|
41
+ | 1-digit | 0% | 0% | 0% |
42
+ | 2-digit | 0% | 0% | 0% |
43
+ | 3-digit | 0% | 0% | 0% |
44
+ | **4-digit (trained)** | **100%** | **100%** | **100%** |
45
+ | 5-digit | 0% | 0% | 0% |
46
+ | 6-digit | 0% | 0% | 0% |
47
+
48
+ Asked `38+86=`, it answers `3+8=11,0+6+1=7,0+6=6,5+8=13,13671` — the carry
49
+ logic runs, but digits are read from *4-digit-trained positions*. Zero
50
+ truncation was measured at every length, so these are genuine wrong answers,
51
+ not context overflows. This is the known failure mode of learned absolute
52
+ positional embeddings: the model learned "the choreography at fixed slots",
53
+ not the arithmetic. Fine for the headline claim (perfect in-distribution at
54
+ 1M params), a real limitation for any generalization claim.
55
+
56
+ ## Baselines (the floor is zero)
57
+
58
+ Both naive baselines score **0.0%** on this task (n=5000):
59
+ - **bigram count model** (next-char probabilities from 10M training tokens)
60
+ - **untrained 1M model** (random weights, greedy decode)
61
+
62
+ Any of the numbers above is therefore entirely learned.
63
+
64
+ ## Honest limitations
65
+
66
+ - **Single task, single format.** Addition only, one chain-of-thought format
67
+ (chosen from a 3-format bake-off: cot 16.6% > left-to-right 15.0% >
68
+ right-to-left 8.7% at 1M/10M tokens, 2-digit). No claims about other tasks.
69
+ - **No length generalization** (table above). Not a bug in evaluation: the
70
+ control row at the trained length re-evaluated to 100% with train-seen
71
+ problems excluded (24 of 2000 dropped, exact RNG replay of the training
72
+ stream).
73
+ - **Contamination is prevented by construction**, not by dedup-after-the-fact:
74
+ both eval sets are built before the training stream, and the stream rejects
75
+ any (a,b) pair appearing in either. Verified programmatically.
76
+ - **Eval n=5000** for headline numbers (±0.6pp at 95%); extrapolation rows
77
+ n≈2000 (±2.2pp at 95%). Where a row shows 0% or 100% the CI is moot.
78
+ - **One seed, one run per cell.** No error bars across seeds.
79
+
80
+ ## Format (what the training text looks like)
81
+
82
+ ```
83
+ 1842+2957=
84
+ 2+7=9,4+5=9,8+9=17,1+2+1=4,4799
85
+ ```
86
+ Digits of each column added right-to-left, carries folded into the next step,
87
+ final answer last (comma-separated), single trailing newline.
88
+
89
+ ## Files
90
+
91
+ - `model.safetensors` / `best.pt` — trained weights (fp32)
92
+ - `curve.csv` — training loss + eval accuracy per checkpoint
93
+ - `summary.json` — final metrics, config, wrong examples
94
+ - Full sweep / bake-off / extrapolation results: see repo `results/`
95
+
96
+ ## Training details
97
+
98
+ | | |
99
+ |---|---|
100
+ | Architecture | decoder-only GPT, d=128, 4 layers, 4 heads, ctx=64, learned absolute positions |
101
+ | Vocab | 16 (digits + `+ - = \n ,` + pad); embedding table = 2,048 params (~0.2% of model) |
102
+ | Params | 1,065,088 |
103
+ | Data | generated on the fly, 1,785,714 problems (~50M tokens), zero eval overlap by construction |
104
+ | Optimizer | AdamW, lr 6e-4, β=(0.9,0.95), wd 0.1, 5% warmup → cosine to 10%, grad clip 1.0 |
105
+ | Eval | greedy decode, strict exact match, n=5000, best checkpoint by tuning-split accuracy |
106
+ | Hardware | 1× Tesla T4 (Kaggle), 2.6 min wall |
107
+ | Frameworks | PyTorch 2.x, no transformers/peft/TRL needed |
108
+
109
+ ## Intended use
110
+
111
+ Educational / research reference point: **a floor measurement for "how small
112
+ can a model be and still learn arithmetic"** — and a cautionary tale that
113
+ in-distribution perfection at this scale is positional pattern-learning, not
114
+ algorithm learning. Compare against real pretrained LLMs before drawing
115
+ conclusions about pretraining vs from-scratch at the 1M–135M scale.
116
+
117
+ ```python
118
+ import torch
119
+ from train import TinyGPT, enc, dec, TOK # train.py in this repo
120
+
121
+ ck = torch.load("best.pt", weights_only=False)
122
+ m = TinyGPT(**{k: ck["cfg"][k] for k in ("d", "L", "H")}, ctx=64)
123
+ m.load_state_dict(ck["model"]); m.eval()
124
+
125
+ def add(a, b):
126
+ ids = torch.tensor([enc(f"{a}+{b}=\n")])
127
+ for _ in range(16):
128
+ nxt = m(ids)[:, -1].argmax(-1, keepdim=True)
129
+ if nxt.item() == TOK["\n"]: break
130
+ ids = torch.cat([ids, nxt], 1)
131
+ text = dec(ids[0, len(f"{a}+{b}=\n"):].tolist())
132
+ return text.split(",")[-1] # cot-format answer
133
+
134
+ print(add(1842, 2957)) # 4799
135
+ ```
bakeoff_results.jsonl ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {"tag": "bo_1m_l2r_2d", "size": "1m", "params": 805632, "fmt": "l2r", "digits": 2, "train_tokens": 10000000, "best_tuning_acc": 0.154, "best_step": 1220, "final_bestckpt_acc": 0.1504, "eval_n": 5000, "wall_min": 0.44878877003987633, "device": "cuda", "wrong_examples": [["63+11=\\n", "55", "74"], ["48+57=\\n", "114", "105"], ["82+65=\\n", "137", "147"], ["30+57=\\n", "86", "87"], ["25+65=\\n", "109", "90"]], "wall_min_run": 0.5413386464118958}
2
+ {"tag": "bo_1m_rtl_2d", "size": "1m", "params": 805632, "fmt": "rtl", "digits": 2, "train_tokens": 10000000, "best_tuning_acc": 0.1, "best_step": 1220, "final_bestckpt_acc": 0.0872, "eval_n": 5000, "wall_min": 0.4464373469352722, "device": "cuda", "wrong_examples": [["63+11=\\n", "17", "74"], ["48+57=\\n", "101", "105"], ["34+44=\\n", "18", "78"], ["82+65=\\n", "141", "147"], ["30+57=\\n", "19", "87"]], "wall_min_run": 0.4470245957374573}
3
+ {"tag": "bo_1m_cot_2d", "size": "1m", "params": 805632, "fmt": "cot", "digits": 2, "train_tokens": 10000000, "best_tuning_acc": 0.157, "best_step": 976, "final_bestckpt_acc": 0.1656, "eval_n": 5000, "wall_min": 0.5330347537994384, "device": "cuda", "wrong_examples": [["63+11=\\n", "3+1=4,1+1=2,24", "74"], ["48+57=\\n", "8+7=15,5+5+1=11,115", "105"], ["34+44=\\n", "4+4=8,2+4=6,68", "78"], ["82+65=\\n", "2+5=7,7+6=13,137", "147"], ["30+57=\\n", "0+7=7,5+5=10,107", "87"]], "wall_min_run": 0.5336322665214539}
4
+ {"tag": "bo_1m_l2r_4d", "size": "1m", "params": 805632, "fmt": "l2r", "digits": 4, "train_tokens": 10000000, "best_tuning_acc": 0.001, "best_step": 488, "final_bestckpt_acc": 0.0, "eval_n": 5000, "wall_min": 0.48135283788045247, "device": "cuda", "wrong_examples": [["7825+1166=\\n", "7000", "8991"], ["5892+7036=\\n", "11000", "12928"], ["4172+5427=\\n", "10000", "9599"], ["8147+3649=\\n", "10000", "11796"], ["7112+3035=\\n", "10011", "10147"]], "wall_min_run": 0.4818975567817688}
5
+ {"tag": "bo_1m_rtl_4d", "size": "1m", "params": 805632, "fmt": "rtl", "digits": 4, "train_tokens": 10000000, "best_tuning_acc": 0.001, "best_step": 610, "final_bestckpt_acc": 0.0, "eval_n": 5000, "wall_min": 0.47441563606262205, "device": "cuda", "wrong_examples": [["7825+1166=\\n", "00001", "8991"], ["5892+7036=\\n", "00001", "12928"], ["4172+5427=\\n", "00001", "9599"], ["8147+3649=\\n", "00001", "11796"], ["7112+3035=\\n", "00001", "10147"]], "wall_min_run": 0.4748885671297709}
6
+ {"tag": "bo_1m_cot_4d", "size": "1m", "params": 805632, "fmt": "cot", "digits": 4, "train_tokens": 10000000, "best_tuning_acc": 0.007, "best_step": 1098, "final_bestckpt_acc": 0.0046, "eval_n": 5000, "wall_min": 0.7503112316131592, "device": "cuda", "wrong_examples": [["7825+1166=\\n", "5+6=10,0+6+1=7,2+1=3,6+1=7,7370", "8991"], ["5892+7036=\\n", "2+6=8,8+3=11,7+0+1=8,5+7=12,12818", "12928"], ["4172+5427=\\n", "2+7=9,0+2=2,7+4=11,1+5+1=7,7129", "9599"], ["8147+3649=\\n", "7+9=16,4+4+1=9,2+6=8,2+3=5,5896", "11796"], ["7112+3035=\\n", "2+5=7,0+3=3,7+0=7,7+3=10,10737", "10147"]], "wall_min_run": 0.7508129199345907}
best.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9fa846343251d69e0d4e147944b616ecedb207c3d7b2970f7fe328bb58ad27a1
3
+ size 3237651
curve.csv ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ step,loss,lr,eval_acc,elapsed_s,tok_per_s
2
+ 610,1.0380,5.96e-04,0.0000,15.3,326115
3
+ 1220,0.6602,5.67e-04,0.6100,30.3,330209
4
+ 1830,0.6154,5.13e-04,0.9060,45.1,332162
5
+ 2440,0.6263,4.39e-04,0.9760,60.1,332463
6
+ 3050,0.6127,3.53e-04,0.9740,75.2,332049
7
+ 3660,0.6131,2.64e-04,1.0000,90.4,331842
8
+ 4270,0.6106,1.83e-04,0.9980,105.4,331818
9
+ 4880,0.6108,1.17e-04,1.0000,120.4,331979
10
+ 5490,0.6092,7.48e-05,1.0000,135.5,332033
11
+ 6100,0.6057,6.00e-05,1.0000,150.5,332027
12
+ 6103,0.6028,6.00e-05,1.0000,151.8,329437
extrapolation.jsonl ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"tag": "sw_1m_4d_50000k", "trained_digits": 4, "test_digits": 1, "acc": 0.0, "correct": 0, "n": 100, "trunc_frac": 0.0, "excluded_seen": 0}
2
+ {"tag": "sw_1m_4d_50000k", "trained_digits": 4, "test_digits": 2, "acc": 0.0, "correct": 0, "n": 2000, "trunc_frac": 0.0, "excluded_seen": 0}
3
+ {"tag": "sw_1m_4d_50000k", "trained_digits": 4, "test_digits": 3, "acc": 0.0, "correct": 0, "n": 2000, "trunc_frac": 0.0, "excluded_seen": 0}
4
+ {"tag": "sw_1m_4d_50000k", "trained_digits": 4, "test_digits": 4, "acc": 1.0, "correct": 1976, "n": 1976, "trunc_frac": 0.0, "excluded_seen": 24}
5
+ {"tag": "sw_1m_4d_50000k", "trained_digits": 4, "test_digits": 5, "acc": 0.0, "correct": 0, "n": 2000, "trunc_frac": 0.0, "excluded_seen": 0}
6
+ {"tag": "sw_1m_4d_50000k", "trained_digits": 4, "test_digits": 6, "acc": 0.0, "correct": 0, "n": 2000, "trunc_frac": 0.0, "excluded_seen": 0}
7
+ {"tag": "sw_5m_4d_50000k", "trained_digits": 4, "test_digits": 1, "acc": 0.0, "correct": 0, "n": 100, "trunc_frac": 0.0, "excluded_seen": 0}
8
+ {"tag": "sw_5m_4d_50000k", "trained_digits": 4, "test_digits": 2, "acc": 0.0, "correct": 0, "n": 2000, "trunc_frac": 0.0, "excluded_seen": 0}
9
+ {"tag": "sw_5m_4d_50000k", "trained_digits": 4, "test_digits": 3, "acc": 0.0, "correct": 0, "n": 2000, "trunc_frac": 0.0, "excluded_seen": 0}
10
+ {"tag": "sw_5m_4d_50000k", "trained_digits": 4, "test_digits": 4, "acc": 1.0, "correct": 1976, "n": 1976, "trunc_frac": 0.0, "excluded_seen": 24}
11
+ {"tag": "sw_5m_4d_50000k", "trained_digits": 4, "test_digits": 5, "acc": 0.0, "correct": 0, "n": 2000, "trunc_frac": 0.0, "excluded_seen": 0}
12
+ {"tag": "sw_5m_4d_50000k", "trained_digits": 4, "test_digits": 6, "acc": 0.0, "correct": 0, "n": 2000, "trunc_frac": 0.0, "excluded_seen": 0}
13
+ {"tag": "sw_8m_4d_50000k", "trained_digits": 4, "test_digits": 1, "acc": 0.0, "correct": 0, "n": 100, "trunc_frac": 0.0, "excluded_seen": 0}
14
+ {"tag": "sw_8m_4d_50000k", "trained_digits": 4, "test_digits": 2, "acc": 0.0, "correct": 0, "n": 2000, "trunc_frac": 0.0, "excluded_seen": 0}
15
+ {"tag": "sw_8m_4d_50000k", "trained_digits": 4, "test_digits": 3, "acc": 0.0, "correct": 0, "n": 2000, "trunc_frac": 0.0, "excluded_seen": 0}
16
+ {"tag": "sw_8m_4d_50000k", "trained_digits": 4, "test_digits": 4, "acc": 1.0, "correct": 1976, "n": 1976, "trunc_frac": 0.0, "excluded_seen": 24}
17
+ {"tag": "sw_8m_4d_50000k", "trained_digits": 4, "test_digits": 5, "acc": 0.0, "correct": 0, "n": 2000, "trunc_frac": 0.0, "excluded_seen": 0}
18
+ {"tag": "sw_8m_4d_50000k", "trained_digits": 4, "test_digits": 6, "acc": 0.0, "correct": 0, "n": 2000, "trunc_frac": 0.0, "excluded_seen": 0}
phase_diagram.png ADDED

Git LFS Details

  • SHA256: 70d625c8716da380f9c5bacd407ba91356940e05f67050ea0cb873ba080f20bf
  • Pointer size: 131 Bytes
  • Size of remote file: 109 kB
summary.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tag": "sw_1m_4d_50000k",
3
+ "size": "1m",
4
+ "params": 805632,
5
+ "fmt": "cot",
6
+ "digits": 4,
7
+ "train_tokens": 50000000,
8
+ "best_tuning_acc": 1.0,
9
+ "best_step": 3660,
10
+ "final_bestckpt_acc": 1.0,
11
+ "eval_n": 5000,
12
+ "wall_min": 2.6284963846206666,
13
+ "device": "cuda",
14
+ "wrong_examples": []
15
+ }
sweep_results.jsonl ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"tag": "sw_1m_4d_2000k", "size": "1m", "params": 805632, "fmt": "cot", "digits": 4, "train_tokens": 2000000, "best_tuning_acc": 0.0, "best_step": 24, "final_bestckpt_acc": 0.0, "eval_n": 5000, "wall_min": 0.4780887484550476, "device": "cuda", "wrong_examples": [["7825+1166=\\n", "6+1=1=1=1=1=1,1,111111111111111111111111111111111111", "8991"], ["5892+7036=\\n", "6=", "12928"], ["4172+5427=\\n", "6=", "9599"], ["8147+3649=\\n", "6=1=1=1=1,111111111111111111111111111111111111111111", "11796"], ["7112+3035=\\n", "6=", "10147"]], "wall_min_run": 0.5785590211550394}
2
+ {"tag": "sw_1m_4d_10000k", "size": "1m", "params": 805632, "fmt": "cot", "digits": 4, "train_tokens": 10000000, "best_tuning_acc": 0.004, "best_step": 976, "final_bestckpt_acc": 0.0022, "eval_n": 5000, "wall_min": 0.7724312980969746, "device": "cuda", "wrong_examples": [["7825+1166=\\n", "5+6=11,1+6+1=8,8+1=9,3+1=4,4981", "8991"], ["5892+7036=\\n", "2+6=8,8+3=11,8+0+1=9,5+7=12,12918", "12928"], ["4172+5427=\\n", "2+7=9,1+2=3,3+4=7,7+5=12,12739", "9599"], ["8147+3649=\\n", "7+9=15,1+4+1=6,3+6=9,3+3=6,6965", "11796"], ["7112+3035=\\n", "2+5=7,1+3=4,2+0=2,3+3=6,6247", "10147"]], "wall_min_run": 0.773020350933075}
3
+ {"tag": "sw_1m_4d_50000k", "size": "1m", "params": 805632, "fmt": "cot", "digits": 4, "train_tokens": 50000000, "best_tuning_acc": 1.0, "best_step": 3660, "final_bestckpt_acc": 1.0, "eval_n": 5000, "wall_min": 2.6284963846206666, "device": "cuda", "wrong_examples": [], "wall_min_run": 2.62900386651357}
4
+ {"tag": "sw_5m_4d_2000k", "size": "5m", "params": 3577728, "fmt": "cot", "digits": 4, "train_tokens": 2000000, "best_tuning_acc": 0.0, "best_step": 24, "final_bestckpt_acc": 0.0, "eval_n": 5000, "wall_min": 2.0082648356755572, "device": "cuda", "wrong_examples": [["7825+1166=\\n", "1+1=1,13+1+1=1,113+1,10+10+1=1=1,1,111113+11+10+1+1=", "8991"], ["5892+7036=\\n", "4+1=1,1+1=1,113+1,1113+111+1+1=1,1+1+1+1=1,1,10+1+1=", "12928"], ["4172+5427=\\n", "4=", "9599"], ["8147+3649=\\n", "1=", "11796"], ["7112+3035=\\n", "4+1=", "10147"]], "wall_min_run": 2.0096086422602335}
5
+ {"tag": "sw_5m_4d_10000k", "size": "5m", "params": 3577728, "fmt": "cot", "digits": 4, "train_tokens": 10000000, "best_tuning_acc": 0.96, "best_step": 1220, "final_bestckpt_acc": 0.957, "eval_n": 5000, "wall_min": 2.8408951918284098, "device": "cuda", "wrong_examples": [["9491+5078=\\n", "9+8=17,9+7+1=17,4+0+1=5,9+5=14,14577", "14569"], ["1578+5504=\\n", "8+4=12,8+0+1=9,5+5=10,1+5+1=7,7092", "7082"], ["8870+1825=\\n", "0+5=5,8+2=10,8+8+1=17,8+1+1=10,10705", "10695"], ["3340+6021=\\n", "0+1=1,3+2=5,3+0=3,3+6=9,9351", "9361"], ["1227+3455=\\n", "7+5=12,5+5+1=11,2+4+1=7,1+3=4,4712", "4682"]], "wall_min_run": 2.8422677516937256}
6
+ {"tag": "sw_5m_4d_50000k", "size": "5m", "params": 3577728, "fmt": "cot", "digits": 4, "train_tokens": 50000000, "best_tuning_acc": 1.0, "best_step": 4270, "final_bestckpt_acc": 0.9998, "eval_n": 5000, "wall_min": 9.716147696971893, "device": "cuda", "wrong_examples": [["1611+4579=\\n", "1+9=10,1+5+1=7,6+5=11,1+4+1=6,6170", "6190"]], "wall_min_run": 9.717524325847625}
7
+ {"tag": "sw_8m_4d_2000k", "size": "8m", "params": 6343168, "fmt": "cot", "digits": 4, "train_tokens": 2000000, "best_tuning_acc": 0.0, "best_step": 24, "final_bestckpt_acc": 0.0, "eval_n": 5000, "wall_min": 2.665485660235087, "device": "cuda", "wrong_examples": [["7825+1166=\\n", "9,1+1+1=1,1111111111111111111111111111111111+11111+1", "8991"], ["5892+7036=\\n", "8,9+1=1,1+11+1+1=1,111111111111111111111111111111111", "12928"], ["4172+5427=\\n", "4,1+1=1,1+1+1=1,1111111111111111111111111111+1111111", "9599"], ["8147+3649=\\n", "4,1+1+1=1,1111+11111111111111111111111111111+11111+1", "11796"], ["7112+3035=\\n", "4,1+1=1,13+1+1=1,111111111111111111111111111+11111+1", "10147"]], "wall_min_run": 2.667503297328949}
8
+ {"tag": "sw_8m_4d_10000k", "size": "8m", "params": 6343168, "fmt": "cot", "digits": 4, "train_tokens": 10000000, "best_tuning_acc": 0.99, "best_step": 1098, "final_bestckpt_acc": 0.9878, "eval_n": 5000, "wall_min": 4.185894413789113, "device": "cuda", "wrong_examples": [["1056+1109=\\n", "6+9=15,5+0+1=6,0+1=1,1+1=2,2655", "2165"], ["8870+1825=\\n", "0+5=5,7+2=9,8+8=16,2+1+1=4,4695", "10695"], ["8812+2518=\\n", "2+8=10,1+1+1=3,8+5=13,9+2+1=12,12330", "11330"], ["8639+7022=\\n", "9+2=11,3+2+1=6,6+0=6,9+7=16,16661", "15661"], ["3108+3309=\\n", "8+9=17,0+0+1=1,1+3=4,4+3=7,7417", "6417"]], "wall_min_run": 4.188009377320608}
9
+ {"tag": "sw_8m_4d_50000k", "size": "8m", "params": 6343168, "fmt": "cot", "digits": 4, "train_tokens": 50000000, "best_tuning_acc": 1.0, "best_step": 4880, "final_bestckpt_acc": 1.0, "eval_n": 5000, "wall_min": 14.382801107565562, "device": "cuda", "wrong_examples": [], "wall_min_run": 14.384850645065308}
10
+ {"tag": "sw_1m_2d_50000k", "size": "1m", "params": 805632, "fmt": "cot", "digits": 2, "train_tokens": 50000000, "best_tuning_acc": 1.0, "best_step": 1830, "final_bestckpt_acc": 1.0, "eval_n": 5000, "wall_min": 2.4130223751068116, "device": "cuda", "wrong_examples": [], "wall_min_run": 2.41362491051356}
11
+ {"tag": "sw_8m_2d_50000k", "size": "8m", "params": 6343168, "fmt": "cot", "digits": 2, "train_tokens": 50000000, "best_tuning_acc": 1.0, "best_step": 2440, "final_bestckpt_acc": 1.0, "eval_n": 5000, "wall_min": 13.12541966040929, "device": "cuda", "wrong_examples": [], "wall_min_run": 13.129189391930899}
train.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tiny arithmetic LM — from-scratch GPT, digit-level vocab, SFT on generated data.
2
+
3
+ Single file, no deps beyond torch+numpy. Runs unchanged on local CPU (dry-run
4
+ preset) and Kaggle T4 (sweep preset).
5
+
6
+ Format experiment (Phase 0b picks the winner):
7
+ l2r : "47+68=\n115\n" answer left-to-right
8
+ rtl : "47+68=\n511\n" answer right-to-left (carry-friendly)
9
+ cot : "47+68=\n7+8=15,4+6+1=11,115\n" digit-wise steps, comma-separated,
10
+ answer = last comma-field. Single trailing newline keeps eval-stopping
11
+ trivial (generate until first '\n').
12
+ """
13
+ import argparse, json, math, os, random, time
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+
21
+ # ---------------------------------------------------------------- tokenizer
22
+ VOCAB = list("0123456789+-=\n,") + ["<pad>"]
23
+ TOK = {c: i for i, c in enumerate(VOCAB)}
24
+ PAD = TOK["<pad>"]
25
+ V = len(VOCAB) # 16
26
+
27
+ def enc(s): return [TOK[c] for c in s]
28
+ def dec(ids): return "".join(VOCAB[i] for i in ids)
29
+
30
+ # ---------------------------------------------------------------- data
31
+ def sample_pair(rng, digits):
32
+ lo, hi = (0, 9) if digits == 1 else (10 ** (digits - 1), 10 ** digits - 1)
33
+ return rng.randint(lo, hi), rng.randint(lo, hi)
34
+
35
+ def format_problem(a, b, ans, fmt):
36
+ if fmt == "l2r":
37
+ return f"{a}+{b}=\n{ans}\n"
38
+ if fmt == "rtl":
39
+ return f"{a}+{b}=\n{str(ans)[::-1]}\n"
40
+ if fmt == "cot":
41
+ sa, sb = str(a), str(b)
42
+ n = max(len(sa), len(sb))
43
+ sa, sb = sa.rjust(n, "0"), sb.rjust(n, "0")
44
+ steps, carry = [], 0
45
+ for i in range(n - 1, -1, -1):
46
+ d1, d2 = int(sa[i]), int(sb[i])
47
+ s = d1 + d2 + carry
48
+ steps.append(f"{d1}+{d2}" + (f"+{carry}" if carry else "") + f"={s}")
49
+ carry = s // 10
50
+ return f"{a}+{b}=\n{','.join(steps)},{ans}\n"
51
+ raise ValueError(fmt)
52
+
53
+ def parse_answer(completion, fmt):
54
+ """completion = generated text after the prompt, before stopping."""
55
+ line = completion.split("\n")[0].strip()
56
+ if not line:
57
+ return None
58
+ if fmt == "rtl":
59
+ return line[::-1]
60
+ if fmt == "cot":
61
+ return line.split(",")[-1]
62
+ return line
63
+
64
+ def max_new_for(fmt, digits=4):
65
+ # cot completion ≈ 9 chars/step + answer; l2r/rtl ≈ answer + newline
66
+ return {"l2r": digits + 4, "rtl": digits + 4, "cot": 10 * digits + 12}[fmt]
67
+
68
+ def make_stream(seed, digits, fmt, eval_set, budget_tokens):
69
+ """Generator of token-id chunks; rejects problems in eval_set
70
+ (guarantees zero train/eval contamination by construction).
71
+ Yields one problem's ids per chunk; constant memory at any budget."""
72
+ py_rng = random.Random(seed)
73
+ n = 0
74
+ while n < budget_tokens:
75
+ a, b = sample_pair(py_rng, digits)
76
+ if (a, b) in eval_set:
77
+ continue
78
+ text = format_problem(a, b, a + b, fmt)
79
+ n += len(text)
80
+ yield enc(text)
81
+
82
+ def make_eval_set(seed, digits, n_problems, exclude=None):
83
+ """Fixed held-out problems. exclude: set of (a,b) pairs to never return
84
+ (used to keep the tuning-eval and final-eval sets disjoint).
85
+ Attempts-guarded: for tiny digit spaces (1-digit = 100 pairs) it returns
86
+ what exists instead of looping forever."""
87
+ rng = random.Random(seed)
88
+ exclude = exclude or set()
89
+ seen, out, attempts = set(), [], 0
90
+ while len(out) < n_problems and attempts < n_problems * 100 + 10_000:
91
+ attempts += 1
92
+ a, b = sample_pair(rng, digits)
93
+ if (a, b) in seen or (a, b) in exclude:
94
+ continue
95
+ seen.add((a, b))
96
+ out.append((a, b))
97
+ return out
98
+
99
+ # ---------------------------------------------------------------- model
100
+ class Block(nn.Module):
101
+ def __init__(self, d, H):
102
+ super().__init__()
103
+ self.ln1 = nn.LayerNorm(d)
104
+ self.qkv = nn.Linear(d, 3 * d)
105
+ self.proj = nn.Linear(d, d)
106
+ self.ln2 = nn.LayerNorm(d)
107
+ self.mlp = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
108
+ self.H = H
109
+ def forward(self, x, mask):
110
+ h = self.ln1(x)
111
+ q, k, v = self.qkv(h).chunk(3, -1)
112
+ B, T, d = q.shape
113
+ hd = d // self.H
114
+ q = q.view(B, T, self.H, hd).transpose(1, 2)
115
+ k = k.view(B, T, self.H, hd).transpose(1, 2)
116
+ v = v.view(B, T, self.H, hd).transpose(1, 2)
117
+ a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, is_causal=mask is None)
118
+ a = a.transpose(1, 2).reshape(B, T, d)
119
+ x = x + self.proj(a)
120
+ x = x + self.mlp(self.ln2(x))
121
+ return x
122
+
123
+ class TinyGPT(nn.Module):
124
+ def __init__(self, d, L, H, ctx=64):
125
+ super().__init__()
126
+ self.emb = nn.Embedding(V, d)
127
+ self.pos = nn.Embedding(ctx, d)
128
+ self.blocks = nn.ModuleList(Block(d, H) for _ in range(L))
129
+ self.ln = nn.LayerNorm(d)
130
+ self.head = nn.Linear(d, V, bias=False)
131
+ self.apply(self._init)
132
+ @staticmethod
133
+ def _init(m):
134
+ if isinstance(m, (nn.Linear, nn.Embedding)):
135
+ nn.init.normal_(m.weight, std=0.02)
136
+ if isinstance(m, nn.Linear) and m.bias is not None:
137
+ nn.init.zeros_(m.bias)
138
+ def forward(self, idx):
139
+ B, T = idx.shape
140
+ p = torch.arange(T, device=idx.device)
141
+ x = self.emb(idx) + self.pos(p)[None]
142
+ for b in self.blocks:
143
+ x = b(x, None)
144
+ return self.head(self.ln(x))
145
+
146
+ SIZES = {
147
+ "1m": dict(d=128, L=4, H=4), # ~1.07M
148
+ "5m": dict(d=192, L=8, H=6), # ~4.76M
149
+ "8m": dict(d=256, L=8, H=8), # ~8.45M
150
+ }
151
+
152
+ def count_params(m): return sum(p.numel() for p in m.parameters())
153
+
154
+ # ---------------------------------------------------------------- eval
155
+ @torch.no_grad()
156
+ def evaluate(model, eval_pairs, fmt, device, batch=256, digits=4, return_trunc=False):
157
+ """Greedy decode, strict exact-match. Returns (acc, n_correct, examples)
158
+ or (..., trunc_frac) when return_trunc=True — trunc_frac = fraction of
159
+ generations that hit the length cap without emitting a newline (needed
160
+ when evaluating beyond trained sequence lengths, where truncation can
161
+ silently masquerade as model failure)."""
162
+ model.eval()
163
+ mx = max_new_for(fmt, digits)
164
+ prompts = [f"{a}+{b}=\n" for a, b in eval_pairs]
165
+ golds = [str(a + b) for a, b in eval_pairs]
166
+ correct, wrong_ex = 0, []
167
+ truncated = 0
168
+ for i in range(0, len(prompts), batch):
169
+ pb = prompts[i:i + batch]
170
+ gb = golds[i:i + batch]
171
+ ids = torch.tensor([enc(p) for p in pb], device=device)
172
+ done = torch.zeros(len(pb), dtype=torch.bool, device=device)
173
+ for _ in range(mx):
174
+ if ids.shape[1] >= model.pos.num_embeddings - 1:
175
+ break # hard stop at positional-embedding limit; never crash
176
+ logits = model(ids)
177
+ nxt = logits[:, -1].argmax(-1, keepdim=True)
178
+ ids = torch.cat([ids, nxt], 1)
179
+ done |= (nxt.squeeze(1) == TOK["\n"])
180
+ if done.all():
181
+ break
182
+ truncated += int((~done).sum())
183
+ for j, (p, g) in enumerate(zip(pb, gb)):
184
+ gen = ids[j, len(p):].tolist()
185
+ comp = []
186
+ for t in gen:
187
+ if t == TOK["\n"]:
188
+ break
189
+ comp.append(t)
190
+ pred = parse_answer(dec(comp), fmt)
191
+ if pred == g:
192
+ correct += 1
193
+ elif len(wrong_ex) < 5:
194
+ wrong_ex.append((p.replace("\n", "\\n"), dec(comp).replace("\n", "\\n"), g))
195
+ model.train()
196
+ if return_trunc:
197
+ return correct / len(prompts), correct, wrong_ex, truncated / len(prompts)
198
+ return correct / len(prompts), correct, wrong_ex
199
+
200
+ # ---------------------------------------------------------------- train
201
+ def train(args):
202
+ device = "cuda" if torch.cuda.is_available() and not args.local else "cpu"
203
+ torch.manual_seed(args.seed)
204
+ rng = random.Random(args.seed)
205
+
206
+ cfg = SIZES[args.size]
207
+ ctx = 64
208
+ model = TinyGPT(cfg["d"], cfg["L"], cfg["H"], ctx).to(device)
209
+ n_params = count_params(model)
210
+
211
+ eval_pairs = make_eval_set(args.seed + 999, args.digits, args.eval_n)
212
+ eval_keys = set(eval_pairs)
213
+ # final eval set created UPFRONT and excluded from training by construction:
214
+ # the stream must never see any problem in either eval set.
215
+ final_pairs = make_eval_set(args.seed + 12345, args.digits, args.eval_final_n,
216
+ exclude=eval_keys)
217
+ final_keys = set(final_pairs)
218
+ train_reject = eval_keys | final_keys
219
+ assert not (final_keys & eval_keys), "final eval overlaps tuning eval!"
220
+
221
+ B, T = args.batch, ctx
222
+ steps = args.tokens // (B * T)
223
+ opt = torch.optim.AdamW(model.parameters(), lr=args.lr, betas=(0.9, 0.95), weight_decay=0.1)
224
+ warm = max(1, int(0.05 * steps))
225
+ sched = torch.optim.lr_scheduler.LambdaLR(
226
+ opt, lambda s: s / warm if s < warm else 0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * (s - warm) / max(1, steps - warm))))
227
+
228
+ stream = make_stream(args.seed, args.digits, args.fmt, train_reject,
229
+ steps * B * (T + 1) + 4096)
230
+ buf = []
231
+
232
+ out = Path(args.out)
233
+ out.mkdir(parents=True, exist_ok=True)
234
+ log_f = open(out / "curve.csv", "w")
235
+ log_f.write("step,loss,lr,eval_acc,elapsed_s,tok_per_s\n")
236
+
237
+ eval_every = max(20, steps // args.eval_points)
238
+ best_acc, best_step = -1.0, -1
239
+ t0 = time.time()
240
+ tok_count = 0
241
+
242
+ for step in range(1, steps + 1):
243
+ while len(buf) < B * (T + 1):
244
+ buf.extend(next(stream))
245
+ batch = torch.tensor(buf[: B * (T + 1)], device=device).view(B, T + 1)
246
+ buf = buf[B * (T + 1):]
247
+ x, y = batch[:, :-1], batch[:, 1:]
248
+ logits = model(x)
249
+ loss = F.cross_entropy(logits.view(-1, V), y.reshape(-1))
250
+ opt.zero_grad()
251
+ loss.backward()
252
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
253
+ opt.step()
254
+ sched.step()
255
+ tok_count += B * T
256
+
257
+ if step % eval_every == 0 or step == steps:
258
+ acc, nc, wrong = evaluate(model, eval_pairs[: args.eval_n], args.fmt, device, digits=args.digits)
259
+ el = time.time() - t0
260
+ tps = tok_count / el
261
+ lr_now = opt.param_groups[0]["lr"]
262
+ log_f.write(f"{step},{loss.item():.4f},{lr_now:.2e},{acc:.4f},{el:.1f},{tps:.0f}\n")
263
+ log_f.flush()
264
+ print(f"[{args.tag}] step {step}/{steps} loss {loss.item():.4f} eval_acc {acc:.4f} "
265
+ f"({el/60:.1f} min, {tps:.0f} tok/s)", flush=True)
266
+ if wrong:
267
+ print(f" sample wrong: {wrong[0]}", flush=True)
268
+ if acc > best_acc:
269
+ best_acc, best_step = acc, step
270
+ torch.save({"model": model.state_dict(), "cfg": cfg, "args": vars(args)},
271
+ out / "best.pt")
272
+ torch.save({"model": model.state_dict(), "cfg": cfg, "args": vars(args)}, out / "final.pt")
273
+
274
+ # final eval on the pre-built held-out set (n=eval_final_n)
275
+ model.load_state_dict(torch.load(out / "best.pt", map_location=device)["model"])
276
+ acc_best, _, wrong_best = evaluate(model, final_pairs, args.fmt, device, digits=args.digits)
277
+ summary = {
278
+ "tag": args.tag, "size": args.size, "params": n_params, "fmt": args.fmt,
279
+ "digits": args.digits, "train_tokens": args.tokens,
280
+ "best_tuning_acc": best_acc, "best_step": best_step,
281
+ "final_bestckpt_acc": acc_best, "eval_n": args.eval_final_n,
282
+ "wall_min": (time.time() - t0) / 60, "device": device,
283
+ "wrong_examples": wrong_best[:10],
284
+ }
285
+ (out / "summary.json").write_text(json.dumps(summary, indent=2))
286
+ print(f"[{args.tag}] DONE best_tuning={best_acc:.4f} final(n={args.eval_final_n})={acc_best:.4f}", flush=True)
287
+ return summary
288
+
289
+ PRESETS = {
290
+ # local dry-run: tiny everything, catches bugs for zero GPU cost
291
+ "local": dict(tokens=50_000, eval_n=30, eval_final_n=50, eval_points=3, batch=32, lr=1e-3),
292
+ # real runs
293
+ "sweep": dict(tokens=10_000_000, eval_n=1000, eval_final_n=5000, eval_points=10, batch=128, lr=6e-4),
294
+ }
295
+
296
+ if __name__ == "__main__":
297
+ ap = argparse.ArgumentParser()
298
+ ap.add_argument("--size", choices=list(SIZES), required=True)
299
+ ap.add_argument("--fmt", choices=["l2r", "rtl", "cot"], required=True)
300
+ ap.add_argument("--digits", type=int, default=4)
301
+ ap.add_argument("--tokens", type=int, default=None)
302
+ ap.add_argument("--lr", type=float, default=None)
303
+ ap.add_argument("--batch", type=int, default=None)
304
+ ap.add_argument("--eval_n", type=int, default=None)
305
+ ap.add_argument("--eval_final_n", type=int, default=None)
306
+ ap.add_argument("--eval_points", type=int, default=None)
307
+ ap.add_argument("--seed", type=int, default=0)
308
+ ap.add_argument("--preset", choices=list(PRESETS), default="sweep")
309
+ ap.add_argument("--local", action="store_true", help="force CPU even if cuda exists")
310
+ ap.add_argument("--out", default=None)
311
+ ap.add_argument("--tag", default=None)
312
+ a = ap.parse_args()
313
+ for k, v in PRESETS[a.preset].items():
314
+ if getattr(a, k) is None:
315
+ setattr(a, k, v)
316
+ a.tag = a.tag or f"{a.size}_{a.fmt}_{a.digits}d_{a.tokens//1000}k"
317
+ a.out = a.out or f"runs/{a.tag}"
318
+ if torch.cuda.is_available() and not a.local:
319
+ torch.backends.cuda.matmul.allow_tf32 = True
320
+ print(json.dumps({k: v for k, v in vars(a).items()}, indent=2), flush=True)
321
+ train(a)