Pre-training a Bengali GPT‑2 From Scratch on a 16GB M1 Mac: Fluent Form, Invented Facts

No CUDA, no WebText, no from_pretrained. A 6.9M-parameter GPT-2, its byte-level BPE tokenizer included, written in plain PyTorch and pre-trained from random weights on Bengali Wikipedia on a single 16GB M1. It learned how a Bengali Wikipedia article is written. It did not learn what is true.
1 Start with the result
The model was scored on the 1,621 Wikipedia articles it never trained on, the same validation split BERT used:
| model | bits per byte |
|---|---|
| uniform: all 8,192 tokens equally likely | 1.3353 |
| unigram: how common each token is, no context | 1.1592 |
| this GPT, after 1,700 steps | 0.6545 |
Bits per byte is the model’s total surprise divided by the size of the text, so it doesn’t depend on how the tokenizer cut the text; GPT-2’s Table 3 uses the same unit. Per token, the same result is a loss of 4.4166 nats, perplexity 82.8: on average the model is as unsure as a fair pick among 83 tokens. None of this compares with English results, because a Bengali letter takes 3 bytes in UTF-8.
Here is what that buys. Given the prompt রবীন্দ্রনাথ ঠাকুর (Rabindranath Tagore), at temperature 0.8 and top-k 40, the first of two samples drawn with seed 1:
রবীন্দ্রনাথ ঠাকুর (জ.০২/১৯০৯) ছিলেন একজন বাঙালি কবি। তার বাবার নাম ছিল রবীন্দ্রনাথ ঠাকুর। তার লেখা বই বাংলা ভাষায় অনুবাদক ছিলেন। তার প্রথম বই, যা ছিল বইটির নাম হল ‘মহংসী নজরুল। তিনি ছিলেন একজন শিক্ষিতযজ্ঞের। তার পিতা ছিলেন রামচন্দ্র চট্টোপাধ্যায়
Rabindranath Tagore (b. 02/1909) was a Bengali poet. His father’s name was Rabindranath Tagore. His written books were translator in the Bengali language. His first book, which was the book’s name is ‘Mahangsi Nazrul. He was an educated-yajna. His father was Ramchandra Chattopadhyay
The form is right. It opens like a Wikipedia biography: the name, a birth date in parentheses after জ. (“born”), “was a Bengali poet”, then his father and his books. Almost every word is a real Bengali word, and the sentences end in ।.
The facts are wrong. Tagore was born in 1861, and his father was Debendranath Tagore. The sample gives 1909 and two other fathers, one of them Tagore himself. The grammar holds for a sentence or two, then slips. The second sample was worse: ঠাকুর, over and over (section 6).
That’s what to expect at this size. GPT-2’s smallest model is 18 times larger and read 40 GB of WebText; this one read 11 million tokens of Bengali Wikipedia, ten times over. So this post stays short, and keeps to what the build turned up: a tokenizer rule that breaks on Bengali, the three changes GPT-2 made to the decoder, and what CUDA’s speed tricks do on a laptop.
2 Same data, same size as BERT, one mask apart
The BERT post ended on one line: bidirectionality is a mask you omit. This post is the other half, the mask passed. GPT trains on the same 16,213 Bengali Wikipedia articles, holds out the same 1,621, and has the same six layers, 256 wide, with eight heads. That makes the two posts one controlled comparison:
| BERT (2018) | GPT-2 (2019) | |
|---|---|---|
| attention | every token sees every token | each token sees only the ones before it |
| trained to | fill in masked tokens; tell whether B follows A | predict the next token, at every position |
| LayerNorm | after each sub-layer | before each sub-layer, plus one at the end |
| tokenizer | WordPiece, 10k | byte-level BPE, 8,192 |
| parameters here | 7,573,266 | 6,901,760 |
| result here | 86.5% on IndicGLUE sna.bn, fine-tuned | 0.6545 bits/byte, and the sample above |
Their losses can’t be compared: BERT predicts 15% of the tokens with both sides visible, GPT predicts every token from the left alone.
What GPT-2 kept from the earlier models is imported unchanged from those posts’ code: LayerNorm and the causal mask from the Transformer, GELU and the weight-decay split from BERT. Everything else is written by hand here: the tokenizer, the attention with its fused QKV, the decoder block, the model, the training loop and the sampler.
3 The architecture
GPT-2 is GPT-1’s decoder, scaled up, with three changes. Here it is at the size that fits a 16GB M1, with আমি কলকাতা যাব (“I will go to Kolkata”) going in at the top:
The whole model is GPT-1’s Eq. 2, with GPT-2’s final LayerNorm added in the last line:
is the token ids, the 8,192 × 256 token table, the 256 × 256 position table. appears twice: the output layer is the token table, transposed. That’s weight tying, the dashed line on the left of the diagram.
Training maximizes GPT-1’s Eq. 1, the log-probability of each token given the ones before it. One forward pass scores all 256 positions at once: the target at each position is the token after it, and the causal mask is what stops a position from seeing that answer.
3.1 What GPT-2 changed
Section 2.3 of the paper changes GPT-1’s block in three sentences, each tagged GPT-2 §2.3 on the diagram:
- LayerNorm moves to the input of each sub-block (pre-norm). The residual stream itself is never normalized, so it runs clean from the embeddings to the top.
- One more LayerNorm after the last block, since nothing else normalizes the stream before the output layer.
- The Linear just before each residual add starts 1/√N smaller, where N counts the adds: two per block, so N = 12 here. Every add makes the un-normalized stream bigger, and the scaling holds that growth down. Measured at initialization, the stream’s standard deviation goes from 0.0283 after the embeddings to 0.0876 after six blocks; with the plain 0.02 init it reaches 0.3152. With 48 blocks the scaled stream ends at 0.0893, nearly the same as with six: its final size barely depends on depth.
The rest is GPT-1: learned positions, GELU, every other weight drawn from N(0, 0.02). The small init shows at step 0. A model that knows nothing should score ln 8,192 = 9.0109, and this one starts at 9.0514.
GPT-2 also widened the vocabulary to 50,257 tokens and the context to 1,024. Both are scaled down here (section 5).
3.2 Where 6,901,760 parameters live
| part | parameters |
|---|---|
token table wte, 8,192 × 256 | 2,097,152 |
position table wpe, 256 × 256 | 65,536 |
| 6 decoder blocks × 789,760 | 4,738,560 |
| final LayerNorm | 512 |
| output layer: the token table again | 0 |
| total | 6,901,760 |
Untied, the output layer would be another 2,097,152 parameters, 23% of an untied model. The token table alone is 30% of it, almost exactly its share of GPT-2 small (31%).
4 A tokenizer that cut Bengali at every vowel sign
GPT-2’s tokenizer works in two steps. A regex first cuts the text into chunks, roughly words. Byte-level BPE then learns merges inside each chunk, never across two, so the regex decides what a token can ever be. OpenAI’s pattern:
's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
Its word class is \p{L}, Unicode letters. In Bengali, only consonants and independent vowels are letters. Vowel signs, the hasanta ্ that builds every conjunct, and the nukta ় are marks, \p{M}. So \p{L}+ stops at every vowel sign, and the sign falls through to the punctuation class:
"আমি কলকাতায় থাকি।" ("I live in Kolkata.")
GPT-2's regex → ['আম', 'ি', ' কলক', 'া', 'ত', 'া', 'য', '়', ' থ', 'া', 'ক', 'ি।']
with \p{M} → ['আমি', ' কলকাতায়', ' থাকি', '।']
Under GPT-2’s pattern, no merge can ever join a consonant to its vowel sign, because the two never share a chunk. On the full corpus it makes 31,022,244 chunks, and the most common is া on its own, 3.0 million times. The fix adds \p{M} to the word class, along with the two zero-width joiners Bengali uses inside words: 8,058,024 chunks, 3.8× fewer, and the most common are now ।, , and এবং (“and”). The English contractions at the front of the pattern are gone too; Bengali has none.
BPE then trains on those chunks. The 256 byte values, 7,935 merges and <|endoftext|> make 8,192 tokens, sized to this corpus rather than GPT-2’s 50,257. A token averages 9.8 bytes of text, about 3.8 Bengali characters. The diagram’s sentence comes out as আ · মি · ␣কলকাতা · ␣যাব: the city is one token, and আমি (“I”) is two only because it opens the text. Mid-sentence, আমি with its space is one token.
5 Training: 4 h 15 m on one M1
GPT-2 states one training number, the batch: 512 sequences of 1,024 tokens. For the rest I used GPT-3’s Appendix B, as Karpathy’s build-nanoGPT does:
| GPT-2 small (paper) | here | |
|---|---|---|
| layers, width, heads | 12, 768, 12 | 6, 256, 8 |
| context | 1,024 | 256 |
| vocabulary | 50,257 | 8,192 |
| parameters | 117M (124M counted) | 6.9M |
| tokens per step | 524,288 | 65,536: 8 micro-batches of 32 × 256 |
| optimizer | not stated | AdamW, β (0.9, 0.95), weight decay 0.1, clip 1.0 |
| learning rate | tuned, value not given | 6e-4, 100 warmup steps, cosine to 10% |
| training text | WebText, 40 GB | Bengali Wikipedia, 11.0M tokens |
| run | not stated | 1,700 steps, 111.4M tokens (10 passes), 4 h 15 m |

Validation loss on all 1.2M held-out tokens, every 100 steps. It improved at all 17 evaluations, so the last checkpoint is the best one. Source: Image by Author, TensorBoard.
Validation loss went from 6.95 at step 100 to 4.4166 at step 1,700, and was still falling when the schedule ran out. Ten passes over the same text had not started to hurt. Gradient clipping fired on 10 of the 1,700 steps, all of them in the warmup. A run interrupted and resumed from its last checkpoint continues with exactly the losses an uninterrupted run would have had.
5.1 What CUDA’s speed tricks do on an M1
build-nanoGPT makes GPT-2 fast on 8 × A100 with bf16, torch.compile and FlashAttention. Measured on the M1, with PyTorch 2.12 on the MPS backend, none of the three helps:
| technique | on the M1 |
|---|---|
| bf16 | 1.7× slower than fp32: the M1’s GPU has no native bf16, so it’s emulated |
torch.compile | about 25% less throughput, after a 270 s first compile |
| FlashAttention | not available. scaled_dot_product_attention runs, but its memory still grows with T²: 4.97 GB at 2,048 tokens (batch 8), out of memory at 8,192 |
That memory curve is why the context here is 256, not 1,024. The run is plain fp32 with SDPA, gradient accumulation, and the token files read through np.memmap, and it averaged about 7,300 tokens a second. One finding is measured but not yet used: fp16 runs a 4,096 × 4,096 matmul 1.24× faster than fp32, and SDPA survives the fp16 overflow behind the Transformer post’s NaN at epoch 4, because it scales before the matmul instead of after.
5.2 Run it yourself
From the repo root, after uv sync:
python -m BERT.scripts.prepare_corpus # Bengali Wikipedia, shared with BERT
python -m GPT.scripts.prepare_corpus # <|endoftext|> after each article
python -m GPT.scripts.train_tokenizer # byte-level BPE, 8,192 tokens, ~5 min
python -m GPT.scripts.prepare_data # encode once: train.bin, val.bin
caffeinate -s python -m GPT.scripts.pretrain # ~4 h 15 m on an M1
python -m GPT.scripts.evaluate # 0.6545 bits/byte
python -m GPT.scripts.generate --prompt "রবীন্দ্রনাথ ঠাকুর"
6 What it learned, and what it didn’t
Taken apart, the held-out loss tells the same story as the sample.
Context helps for about 32 tokens. Loss by position in the 256-token window is 5.711 at the first position, 4.413 at position 32, and 4.340 at the last. Past a few dozen tokens, this model barely uses what it can see, so a longer context would buy little at this size.
Starting a word is the hard part. Tokens that begin a new word cost 5.34 nats on average; tokens that continue one cost 3.31. What the model predicts with confidence is grammar: the sentence-ending ।, হয় (“is”), সালে (“in the year”) after a date, করেন (“does”) closing a sentence. What it can’t predict is which name, number or place comes next, which is exactly where the Tagore sample goes wrong. Almost half of the held-out tokens, 45.4%, got less than a 1% chance.
Greedy decoding loops. At temperature 0, রবীন্দ্রনাথ ঠাকুর continues ঠাকুর ঠাকুর ঠাকুর …, and কলকাতা continues কলকাতা, কলকাতা, কলকাতা, … Once a word repeats, repeating it again is the most likely next token, and greedy always takes the most likely. Over five unconditional samples, only 1% of greedy’s 3-token sequences are distinct, against 82 to 91% when sampling. So generate.yaml samples, with top-k 40 like GPT-2’s own samples. Sampling only makes loops rarer: the second sample at seed 1, at temperature 0.8, was the same ঠাকুর loop.
7 Where it falls short, and what’s next
- It stopped while still learning. Validation loss improved at every evaluation. The cheapest next step is more steps on the same data: raise
max_stepsand resume, and the extra steps run at the schedule’s 10% floor. - Wikipedia is all it has read, so encyclopedia prose is all it can write, and ten passes over 11M tokens is a small, repeated diet. More Bengali text comes before a bigger model.
- No zero-shot evaluation. GPT-2’s headline result is tasks done from a prompt with no fine-tuning (GPT-2 §3): reading comprehension, summarization, translation. This post measures held-out loss and reads samples, nothing more.
- Generation recomputes everything. Without a KV cache, each new token reruns the whole 256-token context: 10.8 ms, about 100 tokens a second. And fp16 (section 5.1) is measured but not wired in.
8 Closing
Same articles, same six layers, one mask apart. The encoder became a classifier that placed above mBERT on a public leaderboard; the decoder became a fluent writer with nothing true to say. At 6.9M parameters that is the honest result, not a bug in the sampler. What’s worth keeping is the build: a tokenizer rule that breaks on a script GPT-2’s regex was never written for, three sentences of GPT-2’s §2.3 measured instead of copied, and a list of CUDA speed tricks that don’t survive the trip to a laptop. The code is on GitHub, one module per file, with every deviation from the paper flagged in configs/base.yaml.
9 References
- Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., Sutskever, I. (2019). Language Models are Unsupervised Multitask Learners. OpenAI. PDF
- Radford, A., Narasimhan, K., Salimans, T., Sutskever, I. (2018). Improving Language Understanding by Generative Pre-Training. OpenAI. PDF
- Brown, T., Mann, B., Ryder, N., et al. (2020). Language Models are Few-Shot Learners. NeurIPS. arXiv:2005.14165. Appendix B is the training recipe used here.
- OpenAI.
gpt-2/src/encoder.py: the original pre-tokenizer regex. - Karpathy, A. build-nanoGPT: GPT-2 124M reproduced on 8 × A100, and the speed techniques measured in section 5.1.
- Sennrich, R., Haddow, B., Birch, A. (2016). Neural Machine Translation of Rare Words with Subword Units. ACL. arXiv:1508.07909
- Holtzman, A., Buys, J., Du, L., Forbes, M., Choi, Y. (2020). The Curious Case of Neural Text Degeneration. ICLR. arXiv:1904.09751
- Unicode Consortium. UAX #44, General Category values: letters (L), marks (M), numbers (N).
- Devlin, J., Chang, M.-W., Lee, K., Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL. arXiv:1810.04805
- Vaswani, A., et al. (2017). Attention Is All You Need. NeurIPS. arXiv:1706.03762