Atharva1232 commited on
Commit
f117e6b
·
verified ·
1 Parent(s): 9feb5f5

tokenizer ablation: digit-split pre-tok = 0.2% -> 99.7% on TinyStories-1M; smallest arithmetic LLM now 3.75M

Browse files
README.md CHANGED
@@ -1,171 +1,79 @@
1
- ---
2
- language: en
3
- tags:
4
- - arithmetic
5
- - tiny-model
6
- - from-scratch
7
- - transformer
8
- - phase-transition
9
- - education
10
- metrics:
11
- - exact_match
12
- library_name: torch
13
- license: apache-2.0
14
- model-index:
15
- - name: tiny-math-1m
16
- results:
17
- - task:
18
- type: text-generation
19
- name: 4-digit addition (chain-of-thought)
20
- dataset:
21
- name: generated addition (held-out, n=5000)
22
- type: generated
23
- metrics:
24
- - type: exact_match
25
- value: 1.0
26
- name: exact match
27
- ---
28
- # tiny-math-1m: a 1M-parameter transformer that adds 4-digit numbers
29
 
30
- **The smallest model in this repo (805,632 parameters, d=128 × 4 layers) solves
31
- 4-digit addition perfectly — 5000/5000 held-out problems, zero errors — given
32
- ~1.8M practice problems. It has a 16-token vocabulary (digits 0-9, `+`, `=`,
33
- newline, comma, pad) and was trained from random initialization. No
34
- pretraining, no demonstrations, no RL. Plain next-token prediction.**
35
 
36
- > **Update (full project completed):** this model was the reference arm of a
37
- > larger study asking *"what is the smallest model that is good at
38
- > arithmetic?"* Final answer: **0.81M from-scratch (this model, 100%)** vs
39
- > **14.1M the smallest real pretrained LLM (pythia-14m, 99.8% after
40
- > fine-tuning on the same 1.78M problems — with only its 1.19M transformer
41
- > blocks trainable)**. LLMs below 14.1M hit a BPE-tokenization floor
42
- > (3.7M → 0.2%, 8.3M → 0%). Zero-shot, every LLM up to 134.5M scores 0%.
43
- > Full tables + chart: see `VERDICT.md` in the GitHub repo.
44
 
45
- ## The finding this repo exists to report
 
 
 
 
 
 
46
 
47
- Three model sizes (1M / 5M / 8M) × three data scales (71k / 357k / 1.78M
48
- practice problems), one task (4-digit addition, chain-of-thought digit steps),
49
- exact-match on held-out problems:
 
 
 
 
50
 
51
- | model | 71k probs | 357k probs | 1.78M probs |
52
- |---|---|---|---|
53
- | **1M** | 0.0% | 0.2% | **100.0%** |
54
- | 5M | 0.0% | 95.7% | 100.0% |
55
- | 8M | 0.0% | 98.8% | 100.0% |
56
-
57
- Two things stand out:
58
-
59
- 1. **The transition is a cliff, not a ramp.** The 1M model sits at 0.2% with
60
- 357k problems and hits 100.0% with 1.78M. No gradual climb — consistent
61
- with the sharp data-scale phase transitions reported in *Teaching Arithmetic
62
- to Small Transformers* (arXiv:2307.03381).
63
- 2. **Bigger models need less practice.** 5M and 8M cross their thresholds by
64
- 357k problems; 1M needs ~5× more data. Capacity buys sample efficiency.
65
-
66
- ## What it learned (and what it didn't)
67
-
68
- The model writes step-by-step carry chains, e.g. for `1842+2957`:
69
- `2+7=9,4+5=9,8+9=17,1+2+1=4,4799` — carries computed correctly, digits
70
- aligned right-to-left. The procedure is real.
71
 
72
- **But it did not learn the addition algorithm.** Quizzed on digit lengths it
73
- never trained on (n≈2000 per row, greedy, same format):
74
 
75
- | tested on | 1M | 5M | 8M |
76
  |---|---|---|---|
77
- | 1-digit | 0% | 0% | 0% |
78
- | 2-digit | 0% | 0% | 0% |
79
- | 3-digit | 0% | 0% | 0% |
80
- | **4-digit (trained)** | **100%** | **100%** | **100%** |
81
- | 5-digit | 0% | 0% | 0% |
82
- | 6-digit | 0% | 0% | 0% |
83
-
84
- Asked `38+86=`, it answers `3+8=11,0+6+1=7,0+6=6,5+8=13,13671` — the carry
85
- logic runs, but digits are read from *4-digit-trained positions*. Zero
86
- truncation was measured at every length, so these are genuine wrong answers,
87
- not context overflows. This is the known failure mode of learned absolute
88
- positional embeddings: the model learned "the choreography at fixed slots",
89
- not the arithmetic. Fine for the headline claim (perfect in-distribution at
90
- 1M params), a real limitation for any generalization claim.
91
-
92
- ## Baselines (the floor is zero)
93
-
94
- Both naive baselines score **0.0%** on this task (n=5000):
95
- - **bigram count model** (next-char probabilities from 10M training tokens)
96
- - **untrained 1M model** (random weights, greedy decode)
97
-
98
- Any of the numbers above is therefore entirely learned.
99
 
100
- ## Honest limitations
101
 
102
- - **Single task, single format.** Addition only, one chain-of-thought format
103
- (chosen from a 3-format bake-off: cot 16.6% > left-to-right 15.0% >
104
- right-to-left 8.7% at 1M/10M tokens, 2-digit). No claims about other tasks.
105
- - **No length generalization** (table above). Not a bug in evaluation: the
106
- control row at the trained length re-evaluated to 100% with train-seen
107
- problems excluded (24 of 2000 dropped, exact RNG replay of the training
108
- stream).
109
- - **Contamination is prevented by construction**, not by dedup-after-the-fact:
110
- both eval sets are built before the training stream, and the stream rejects
111
- any (a,b) pair appearing in either. Verified programmatically.
112
- - **Eval n=5000** for headline numbers (±0.6pp at 95%); extrapolation rows
113
- n≈2000 (±2.2pp at 95%). Where a row shows 0% or 100% the CI is moot.
114
- - **One seed, one run per cell.** No error bars across seeds.
115
 
116
- ## Format (what the training text looks like)
117
 
118
  ```
119
- 1842+2957=
120
- 2+7=9,4+5=9,8+9=17,1+2+1=4,4799
 
 
 
 
 
 
 
 
121
  ```
122
- Digits of each column added right-to-left, carries folded into the next step,
123
- final answer last (comma-separated), single trailing newline.
124
-
125
- ## Files
126
-
127
- - `model.safetensors` / `best.pt` — trained weights (fp32)
128
- - `curve.csv` — training loss + eval accuracy per checkpoint
129
- - `summary.json` — final metrics, config, wrong examples
130
- - Full sweep / bake-off / extrapolation results: see repo `results/`
131
-
132
- ## Training details
133
-
134
- | | |
135
- |---|---|
136
- | Architecture | decoder-only GPT, d=128, 4 layers, 4 heads, ctx=64, learned absolute positions |
137
- | Vocab | 16 (digits + `+ - = \n ,` + pad); embedding table = 2,048 params (~0.2% of model) |
138
- | Params | 805,632 (torch count; "1M" is the size-class label) |
139
- | Data | generated on the fly, 1,785,714 problems (~50M tokens), zero eval overlap by construction |
140
- | Optimizer | AdamW, lr 6e-4, β=(0.9,0.95), wd 0.1, 5% warmup → cosine to 10%, grad clip 1.0 |
141
- | Eval | greedy decode, strict exact match, n=5000, best checkpoint by tuning-split accuracy |
142
- | Hardware | 1× Tesla T4 (Kaggle), 2.6 min wall |
143
- | Frameworks | PyTorch 2.x, no transformers/peft/TRL needed |
144
-
145
- ## Intended use
146
-
147
- Educational / research reference point: **a floor measurement for "how small
148
- can a model be and still learn arithmetic"** — and a cautionary tale that
149
- in-distribution perfection at this scale is positional pattern-learning, not
150
- algorithm learning. Compare against real pretrained LLMs before drawing
151
- conclusions about pretraining vs from-scratch at the 1M–135M scale.
152
-
153
- ```python
154
- import torch
155
- from train import TinyGPT, enc, dec, TOK # train.py in this repo
156
-
157
- ck = torch.load("best.pt", weights_only=False)
158
- m = TinyGPT(**{k: ck["cfg"][k] for k in ("d", "L", "H")}, ctx=64)
159
- m.load_state_dict(ck["model"]); m.eval()
160
-
161
- def add(a, b):
162
- ids = torch.tensor([enc(f"{a}+{b}=\n")])
163
- for _ in range(16):
164
- nxt = m(ids)[:, -1].argmax(-1, keepdim=True)
165
- if nxt.item() == TOK["\n"]: break
166
- ids = torch.cat([ids, nxt], 1)
167
- text = dec(ids[0, len(f"{a}+{b}=\n"):].tolist())
168
- return text.split(",")[-1] # cot-format answer
169
 
170
- print(add(1842, 2957)) # 4799
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  ```
 
1
+ # tiny-math
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ **How small can a model be and still learn arithmetic? — answered.**
 
 
 
 
4
 
5
+ | | smallest that passes (≥95% on 4-digit addition) | accuracy |
6
+ |---|---|---|
7
+ | **From-scratch** (digit vocab) | **805,632 params** | **100.0%** (5000/5000) |
8
+ | **Real pretrained LLM** (fine-tuned, minimal tokenizer fix) | **TinyStories-1M, 3.75M params** | **99.7%** (n=2000) |
9
+ | Real pretrained LLM (native BPE, no tokenizer change) | pythia-14m, 14.1M params | 99.8% (n=2000) |
 
 
 
10
 
11
+ **The closing experiment: a one-rule tokenizer ablation moved TinyStories-1M
12
+ from 0.2% → 99.7%** — same weights, same data, same recipe; only change:
13
+ number runs tokenize per digit instead of inconsistent chunks
14
+ (`1842 → ['18','42']` native vs `['1','8','4','2']` fixed), same 50,257
15
+ vocab, no new tokens. The BPE floor was never about capacity — it was the
16
+ tokenizer's chop points. Zero-shot, every real LLM up to 134.5M still
17
+ scores **0%**. Full story: **[VERDICT.md](VERDICT.md)**.
18
 
19
+ Three structural findings: (1) capacity buys sample efficiency and the
20
+ transition is a **cliff** (0.81M: 0.2% → 100% between 357k and 1.78M
21
+ problems); (2) in-distribution perfection ≠ algorithm learning — 100% at
22
+ the trained digit-length, **0% at every other length**, with example
23
+ answers showing fixed-slot positional choreography; (3) pythia-14m's 99.8%
24
+ trained only its **1.19M transformer blocks** (vocab frozen) — nearly the
25
+ same trainable capacity as the from-scratch winner.
26
 
27
+ [Model + full results on Hugging Face](https://huggingface.co/Atharva1232/tiny-math-1m)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
+ ## Headline from-scratch results
 
30
 
31
+ | model (actual params) | 71k problems | 357k problems | 1.78M problems |
32
  |---|---|---|---|
33
+ | **0.81M** | 0.0% | 0.2% | **100.0%** |
34
+ | 3.58M | 0.0% | 95.7% | 100.0% |
35
+ | 6.34M | 0.0% | 98.8% | 100.0% |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
+ ![phase diagram](phase_diagram.png)
38
 
39
+ Baselines (bigram count model, untrained model): **0.0%** — the floor is
40
+ zero; everything above it is learned.
 
 
 
 
 
 
 
 
 
 
 
41
 
42
+ ## Layout
43
 
44
  ```
45
+ VERDICT.md # the final answer: tables, chart, disclosures
46
+ train.py # tokenizer + data gen (3 formats) + TinyGPT + train/eval loop
47
+ baselines.py # bigram count model + untrained-model baselines
48
+ verdict.py # combines ALL results -> verdict.json + verdict_chart.png
49
+ make_kernel.py # builds single-file Kaggle kernels (no sibling imports)
50
+ nan_autopsy.py # fp16/AdamW NaN forensics (the pythia-14m saga)
51
+ MODEL_CARD.md # honest report for the from-scratch model
52
+ STATUS.md # full session log: bugs found, decisions, pre-committed rules
53
+ kernels/ # every GPU run: bakeoff, sweep, extrapol, quiz, stageb2-6
54
+ results/ # all raw results + charts
55
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ ## Methodology notes (the parts that matter)
58
+
59
+ - **Contamination prevented by construction**: eval sets built before
60
+ training streams; streams reject any eval pair; extrapolation control
61
+ excludes train-seen pairs by exact RNG replay.
62
+ - **Exact match only**, never training loss or shaped rewards.
63
+ - **Format chosen by measurement** (3-format bake-off), not taste.
64
+ - **Independent tuning vs final eval sets** with overlap asserts.
65
+ - Eval sizes stated per table (n=5000 from-scratch, n=2000 LLMs).
66
+ - One seed per cell; disclosed. Six training rounds for the LLM arm —
67
+ every null result, bug, and fix is in `STATUS.md`. Nothing was dropped
68
+ for being inconvenient.
69
+
70
+ ## Citation
71
+
72
+ ```bibtex
73
+ @misc{atharvagupta123-tiny-math,
74
+ title = {tiny-math: the smallest model that can do arithmetic (0.81M from scratch; 14.1M as a pretrained LLM)},
75
+ author = {Atharva Gupta},
76
+ year = {2026},
77
+ howpublished = {\url{https://github.com/Its-Atharva-Gupta/tiny-math}}
78
+ }
79
  ```
STATUS.md CHANGED
@@ -199,6 +199,25 @@ then invents more problems; lenient=0 because last number is hallucination).
199
  headline — escalating it cannot change the "smallest" answer, skipped
200
  (quota discipline, reason recorded).
201
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  ## Timeline
203
  - 23:0x Phase 0 done: train.py + baselines.py + unit tests all pass. Local
204
  2-digit 2M-token run proved learning (loss 2.08→1.34, acc 0→~2% on l2r;
 
199
  headline — escalating it cannot change the "smallest" answer, skipped
200
  (quota discipline, reason recorded).
201
 
202
+ ## TOKENIZER ABLATION (user request, RUNNING — kernel tiny-math-tokablation)
203
+ One-variable experiment: TinyStories-1M, native BPE scored strict 0.002 @
204
+ 1.78M problems (control r2_ts1m_1780k). Treatment = SMALLEST tokenizer
205
+ change: number runs split PER DIGIT (pre-tok `?\\p{N}+` -> `?\\d`), same
206
+ 50,257 vocab, SAME embedding matrix, no new tokens, no resize. Everything
207
+ else frozen: same checkpoint, same 1.78M problems, same fp16/lr 6e-5/
208
+ batch-32 recipe, same eval sets (tune 7781 / final 7782).
209
+ - Local validation done: OLD chops `1842 -> ['18','42']`, `9920 -> ['99','20']`
210
+ (inconsistent boundaries — the mechanism we suspected); NEW gives one
211
+ token per digit; 500-string round-trip check passed; alphabet closed,
212
+ no spaces (chunk-interaction assumption holds).
213
+ - Compute: digit-split = 1.23x tokens/problem (36.9 -> 45.4), disclosed as
214
+ a consequence of the treatment (same problems, ~1.23x steps).
215
+ - PRE-REGISTERED PREDICTIONS: BPE-chunking was THE wall -> big jump
216
+ (>>10%, plausibly 90%+; from-scratch 806K hit 100% on same data);
217
+ tokenization was not it -> <5% (wall = pretraining/capacity).
218
+ - Implementation: per-char id dict == patched-pretokenizer for this corpus
219
+ (single-char chunk = BPE identity), asserted in-kernel at startup.
220
+
221
  ## Timeline
222
  - 23:0x Phase 0 done: train.py + baselines.py + unit tests all pass. Local
223
  2-digit 2M-token run proved learning (loss 2.08→1.34, acc 0→~2% on l2r;
VERDICT.md CHANGED
@@ -3,17 +3,39 @@
3
  **The question:** find the smallest model that is genuinely good at
4
  4-digit addition (exact-match on held-out problems, greedy decoding).
5
 
6
- **The answer — two numbers, one task:**
7
 
8
  | | smallest that passes (≥95%) | accuracy | training data |
9
  |---|---|---|---|
10
  | **From-scratch model** (digit vocab) | **805,632 params** | **100.0%** (5000/5000) | 1.78M problems |
11
- | **Real pretrained LLM** (fine-tuned) | **pythia-14m, 14.1M params** | **99.8%** (n=2000) | 1.78M problems |
12
-
13
- And the floor is brutal in between: **zero-shot, every real LLM up to
14
- 134.5M params scores 0%**; fine-tuned, LLMs below ~14M hit a
15
- BPE-tokenization wall (3.7M → 0.2%, 8.3M → 0%) even with enough data that
16
- an 0.81M from-scratch model reaches 100%.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  ![verdict chart](verdict_chart.png)
19
 
 
3
  **The question:** find the smallest model that is genuinely good at
4
  4-digit addition (exact-match on held-out problems, greedy decoding).
5
 
6
+ **The answer — two numbers, one task (refined by the tokenizer ablation):**
7
 
8
  | | smallest that passes (≥95%) | accuracy | training data |
9
  |---|---|---|---|
10
  | **From-scratch model** (digit vocab) | **805,632 params** | **100.0%** (5000/5000) | 1.78M problems |
11
+ | **Real pretrained LLM** (fine-tuned, minimal tokenizer fix) | **TinyStories-1M, 3.75M params** | **99.7%** (n=2000) | 1.78M problems |
12
+ | Real pretrained LLM (fine-tuned, NATIVE BPE tokenizer) | pythia-14m, 14.1M params | 99.8% (n=2000) | 1.78M problems |
13
+
14
+ **The tokenizer ablation (the study's closing experiment) — one variable,
15
+ 500× swing.** TinyStories-1M, same checkpoint, same 1.78M problems, same
16
+ fp16/lr/batch recipe, same eval sets; the ONLY change was splitting number
17
+ runs per digit in the pre-tokenizer (same 50,257-entry vocab, same
18
+ embedding matrix, no new tokens):
19
+
20
+ | tokenizer | strict accuracy |
21
+ |---|---|
22
+ | native BPE (`1842 → ['18','42']`, `9920 → ['99','20']` — inconsistent boundaries) | **0.2%** |
23
+ | digit-split (`1842 → ['1','8','4','2']`, one rule: `\p{N}+` → `\d`) | **99.7%** |
24
+
25
+ The BPE floor is not a capacity floor and not a pretraining floor — it is
26
+ *literally the tokenizer chopping numbers at inconsistent boundaries*.
27
+ Fix the boundaries, and the smallest real LLM in the study solves
28
+ arithmetic at 3.75M params. (Cost: 1.23× tokens per problem, 36.9 → 45.5.)
29
+ pythia-14m's native-BPE success at 14.1M is now explained as The Pile's
30
+ math/code exposure grinding through the inconsistency at larger scale —
31
+ the tokenizer fix makes it unnecessary.
32
+
33
+ And the floor is brutal in between (all runs with **native BPE** tokenizers):
34
+ **zero-shot, every real LLM up to 134.5M params scores 0%**; fine-tuned,
35
+ LLMs below ~14M hit a BPE-tokenization wall (3.7M → 0.2%, 8.3M → 0%) even
36
+ with enough data that an 0.81M from-scratch model reaches 100% — *unless
37
+ the tokenizer is fixed, which collapses the floor entirely* (ablation
38
+ above: 3.7M → 99.7% with one pre-tokenizer rule).
39
 
40
  ![verdict chart](verdict_chart.png)
41
 
stage_b_round7_tokablation.jsonl ADDED
@@ -0,0 +1 @@
 
 
1
+ {"model": "roneneldan/TinyStories-1M", "params": 3745984, "n_problems": 1780000, "tokenizer": "digit-split (same 50257 vocab; pre-tok number runs -> per-digit)", "control_tag": "r2_ts1m_1780k (native BPE) = 0.002 strict", "tokens_per_problem": 45.541537078651686, "fp16": true, "lr": 6e-05, "best": {"strict": 0.997, "lenient": 0.0, "step": 9895}, "final_strict": 0.991, "final_lenient": 0.0, "wrong_examples": [["8857+7132", "7+2=9,5+3=8,8+1=9,8+7=15,15989\\n7941+1916=\\n1+6=7,4+1=5,9+9=18,7+1+1=9,9857\\n7944+1244=\\n4+4=8", "15989"], ["2052+2983", "2+3=5,5+8=13,0+9+1=10,2+2+1=5,5035\\n1116+1104=\\n6+4=10,1+0+1=2,1+1=2,1+1=2,2220\\n1044+2424=\\n4", "5035"], ["8878+6083", "8+3=11,7+8+1=16,8+0+1=9,8+6=14,14961\\n1111+1164=\\n1+4=5,1+6=7,1+1=2,1+1=2,2275\\n2441+2724=\\n1+", "14961"], ["7833+6471", "3+1=4,3+7=10,8+4+1=13,7+6+1=14,14304\\n1111+1116=\\n1+6=7,1+1=2,1+1=2,1+1=2,2227\\n1111+2224=\\n1+", "14304"]], "lang_samples": {"Once upon a time": "=1,1+9=8,1+7=8,8+7=15,15881\n1116+2416=\n6+6=12,1+1+1=3,1+4=5,", "The capital of France is": "1=1=\n90+40=9,1+0=1,7+4=11,11199\n1118+2172=\n8+2=10,1+7+1=9,1+"}, "grad_norm_max": 497.95947265625, "wall_min": 42.301463878154756, "tag": "r7_ts1m_digitsplit_1780k"}
tokenizer_ablation_check.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Verify the minimal digit-split tokenizer for the ablation (public API only).
3
+
4
+ The minimal change: pre-tokenizer splits number runs PER DIGIT instead of
5
+ whole runs (GPT-2 pattern `?\\p{N}+` -> `?\\d`). Because a single-char chunk
6
+ under BPE is identity, this is exactly equivalent to looking each character
7
+ up in the existing vocab — same 50,257 entries, same embedding matrix,
8
+ zero new tokens.
9
+
10
+ Checks:
11
+ 1. CONTROL: original tokenizer absorbs numbers as chunks (the problem).
12
+ 2. New path: per-char dict round-trips on the full cot alphabet.
13
+ 3. Equivalence argument, tested where testable: for every single char,
14
+ original.encode(char) == our fast id (single-char chunks behave the
15
+ same under old and new pattern); our corpus has no spaces (asserted),
16
+ so no chunk-boundary interaction can occur.
17
+ 4. Effect size: tokens-per-problem, old vs new.
18
+ """
19
+ import random
20
+ from transformers import AutoTokenizer
21
+
22
+ def cot(a, b):
23
+ sa, sb = str(a).rjust(4, "0"), str(b).rjust(4, "0")
24
+ steps, carry = [], 0
25
+ for i in range(3, -1, -1):
26
+ d1, d2 = int(sa[i]), int(sb[i])
27
+ s = d1 + d2 + carry
28
+ steps.append(f"{d1}+{d2}" + (f"+{carry}" if carry else "") + f"={s}")
29
+ carry = s // 10
30
+ return f"{a}+{b}=\n{','.join(steps)},{a+b}\n"
31
+
32
+ def main():
33
+ tok = AutoTokenizer.from_pretrained("roneneldan/TinyStories-1M")
34
+ vocab_size = len(tok.get_vocab())
35
+ print(f"vocab size: {vocab_size} (UNCHANGED by our patch — no new tokens, no resize)")
36
+
37
+ # 1. control: how numbers encode today
38
+ for num in ["47", "15", "115", "1842", "9920"]:
39
+ ids = tok.encode(num, add_special_tokens=False)
40
+ print(f" ORIGINAL: {num!r} -> {len(ids)} token(s) {ids} decode={[tok.decode([i]) for i in ids]}")
41
+
42
+ # 2. build the digit-split dict over the full cot alphabet, round-trip check
43
+ alphabet = "0123456789+=,\n"
44
+ D = {}
45
+ for ch in alphabet:
46
+ ids = tok.encode(ch, add_special_tokens=False)
47
+ assert len(ids) == 1, f"single char {ch!r} mapped to {ids}"
48
+ assert tok.decode(ids) == ch, f"roundtrip fail for {ch!r}"
49
+ D[ch] = ids[0]
50
+ print(f"\nalphabet dict built: {len(D)} chars, all round-trip OK")
51
+
52
+ def enc(text):
53
+ return [D[c] for c in text]
54
+
55
+ # 3. corpus assumptions
56
+ rng = random.Random(0)
57
+ old_n = new_n = 0
58
+ for _ in range(500):
59
+ a, b = rng.randint(1000, 9999), rng.randint(1000, 9999)
60
+ t = cot(a, b)
61
+ assert " " not in t, "cot text contains a space — chunk-interaction assumption broken"
62
+ assert set(t) <= set(alphabet), f"unexpected chars: {set(t)-set(alphabet)}"
63
+ old = tok.encode(t, add_special_tokens=False)
64
+ new = enc(t)
65
+ assert tok.decode(new) == t, "new-path decode mismatch"
66
+ old_n += len(old); new_n += len(new)
67
+ print(f"500 cot strings: decode(new)==original OK; no spaces, alphabet closed")
68
+ print(f"tokens/problem: OLD={old_n/500:.1f} NEW={new_n/500:.1f} "
69
+ f"(x{new_n/old_n:.2f} — digit-splitting costs ~this much extra compute)")
70
+
71
+ # 4. the property itself, one example side by side
72
+ ex = cot(1842, 2957)
73
+ print(f"\nexample {ex.splitlines()[0]!r}:")
74
+ print(f" OLD pieces: {[tok.decode([i]) for i in tok.encode(ex, add_special_tokens=False)][:16]}")
75
+ print(f" NEW pieces: {[tok.decode([i]) for i in enc(ex)][:16]}")
76
+ print("\nVERDICT: digit-split tokenizer validated (same vocab, numbers now per-digit)")
77
+
78
+ if __name__ == "__main__":
79
+ main()