Text Generation
Transformers
Safetensors
English
llama
gpt-u
tiny-lm
pretrained-from-scratch
text-generation-inference
DedeProGames commited on
Commit
13caab9
·
verified ·
1 Parent(s): 3af5295

GPT-U-20M: final weights, tokenizer, model card, scripts and logs

Browse files
.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
+ out/loss.png filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ datasets:
4
+ - mlfoundations/dclm-baseline-1.0
5
+ - HuggingFaceFW/fineweb-edu
6
+ - HuggingFaceCode/stack-v3-train
7
+ language: en
8
+ library_name: transformers
9
+ pipeline_tag: text-generation
10
+ tags:
11
+ - gpt-u
12
+ - tiny-lm
13
+ - pretrained-from-scratch
14
+ ---
15
+
16
+ # GPT-U-20M
17
+
18
+ A 20.5M-parameter Llama-architecture language model pretrained from scratch on 2.6B tokens of web text, educational text and code.
19
+
20
+ ## Architecture
21
+
22
+ | | |
23
+ |---|---|
24
+ | Type | decoder-only transformer, `LlamaForCausalLM`: RoPE, SwiGLU, RMSNorm, pre-norm, no biases |
25
+ | Parameters | 20,453,760 (6,291,456 tied embedding + 8 × 1,770,240 per block + 384 final norm) |
26
+ | Layers | 8 |
27
+ | Hidden size | 384 |
28
+ | Attention | 6 heads × 64 dims, full multi-head (no GQA), SDPA |
29
+ | MLP | SwiGLU, intermediate size 1,024 |
30
+ | Vocabulary | 16,384 (byte-level BPE, trained on the same mix) |
31
+ | Context length | 1,024 tokens |
32
+ | RoPE θ | 10,000 |
33
+ | Input/output embeddings | tied |
34
+
35
+ The 16,384-token vocabulary keeps the embedding at 31% of the parameters (a 50k vocabulary would need 19.3M parameters at width 384) and lets tokens be stored as `uint16`.
36
+
37
+ **Tokenizer.** Byte-level BPE with a cl100k-style split that keeps whitespace runs whole (Python indentation), one token per digit, and `<|endoftext|>` (id 0) as BOS/EOS/padding. Round-trip `decode(encode(x)) == x` holds on 1,000 held-out samples (tabs, CRLF, emoji, CJK, RTL, control characters).
38
+
39
+ | Held-out domain | Tokens / word | Bytes / token |
40
+ |---|---:|---:|
41
+ | DCLM | 1.48 | 4.07 |
42
+ | FineWeb-Edu | 1.45 | 4.24 |
43
+ | Code (27% Python) | 5.34 | 2.01 |
44
+ | Python only | 3.78 | 3.21 |
45
+
46
+ ## Training data
47
+
48
+ One epoch over 2.6B tokens, no repetition:
49
+
50
+ | Dataset | Target share | Realized share | Tokens seen (≈) |
51
+ |---|---:|---:|---:|
52
+ | [mlfoundations/dclm-baseline-1.0](https://huggingface.co/datasets/mlfoundations/dclm-baseline-1.0) | 45% | 45.04% | 1.17B |
53
+ | [HuggingFaceFW/fineweb-edu](https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu) (`sample-10BT`) | 35% | 35.03% | 0.91B |
54
+ | [HuggingFaceCode/stack-v3-train](https://huggingface.co/datasets/HuggingFaceCode/stack-v3-train) | 20% | 19.93% | 0.52B |
55
+
56
+ - Each source is streamed from the Hub and tokenized up to its token budget; the documents are then interleaved **per document** in a seeded random order, i.e. with fixed proportions for the whole run (no domain curriculum), so the realized shares match the targets exactly. (Holding the four streams open at once was avoided: it needed 7–8 GB of RAM and destabilized the training machine.)
57
+ - The Stack v3 is grouped by repository; repositories were split into individual files, vendored files dropped, and Python held at 26.6% of the code tokens (it is ~4% of Stack v3 naturally).
58
+ - Documents are separated by `<|endoftext|>` and packed into contiguous 1,025-token blocks (1,024 inputs + 1 shifted target), no padding. Batches are sampled from a seeded permutation of all blocks.
59
+ - Validation holdouts (2M tokens per domain) come from source files that never fed training or the tokenizer.
60
+
61
+ ## Training
62
+
63
+ | Hyperparameter | Value |
64
+ |---|---|
65
+ | Tokens per step | 131,072 (2 GPUs × 32 sequences × 1,024 tokens × 2 accumulation steps) |
66
+ | Steps | 19,840 |
67
+ | Optimizer | AdamW, β = (0.9, 0.95), ε = 1e-8 |
68
+ | Peak learning rate | 1.8e-3 |
69
+ | Schedule | WSD: 500 warmup steps → constant to step 15,872 → linear decay to 1.8e-4 at step 19,840 |
70
+ | Weight decay | 0.1 on 2D matrices only (none on norms and embeddings) |
71
+ | Gradient clipping | 1.0 |
72
+ | z-loss | 1e-4 |
73
+ | Dropout | 0 |
74
+ | Initialization | N(0, 0.02); `o_proj` and `down_proj` scaled by 1/√(2·8) |
75
+ | Precision | bf16 autocast, fp32 master weights |
76
+
77
+ Trained on 2× RTX 3060 12GB (no NVLink) under WSL2 with PyTorch DDP and `torch.compile` (mode: compile): 4.6 h of active training time, 167,893 tokens/s on average (MFU ≈ 52% of the GPUs' measured bf16 matmul throughput), max GPU temperature 76°C, 3 automatic resume(s) from checkpoints after the machine was shut down, 0 loss-spike rollback(s).
78
+
79
+ ## Results
80
+
81
+ Validation loss on the 2M-token holdouts (1,600 fixed 1,024-token windows per domain) and bits per byte, `bpb = loss_nats × tokens / (bytes × ln 2)`, which is comparable across tokenizers:
82
+
83
+ | Domain | Val loss (nats/token) | Bits per byte |
84
+ |---|---:|---:|
85
+ | DCLM-baseline | 3.5044 | 1.2377 |
86
+ | FineWeb-Edu | 3.2586 | 1.1070 |
87
+ | The Stack v3 (code) | 1.8075 | 1.3031 |
88
+ | **Aggregate** | **2.8568** | **1.1967** |
89
+
90
+ The aggregate is the equal-weight mean of the three holdouts (same number of tokens each). Code tokens are far easier to predict than prose with this tokenizer, which pulls the aggregate down; the prose domains (3.26–3.50 nats/token) are the fairer comparison point for web-text models, and bits per byte is the fairer one across tokenizers.
91
+
92
+ Zero-shot benchmarks ([lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness)). `<|endoftext|>` is prepended as BOS. hellaswag and winogrande sit at chance, as expected at 20M parameters; arc_easy and piqa land clearly above it, which reflects surface lexical knowledge more than reasoning. They are reported for transparency, not as a quality signal.
93
+
94
+ | Task | Metric | GPT-U-20M | Chance |
95
+ |---|---|---:|---:|
96
+ | arc_easy | acc | 40.03 | 25 |
97
+ | arc_easy | acc_norm | 37.42 | 25 |
98
+ | piqa | acc | 58.60 | 50 |
99
+ | piqa | acc_norm | 58.54 | 50 |
100
+ | hellaswag | acc | 26.64 | 25 |
101
+ | hellaswag | acc_norm | 27.85 | 25 |
102
+ | lambada_openai | acc | 21.79 | 0 |
103
+ | lambada_openai | perplexity | 138.45 | — |
104
+ | winogrande | acc | 51.78 | 50 |
105
+
106
+ Sample generations (temperature 0.8, top-p 0.95) are in [`out/samples.md`](out/samples.md).
107
+
108
+ ## Loss curve
109
+
110
+ ![Training and validation loss](out/loss.png)
111
+
112
+ ## Usage
113
+
114
+ ```python
115
+ import torch
116
+ from transformers import AutoModelForCausalLM, AutoTokenizer
117
+
118
+ tokenizer = AutoTokenizer.from_pretrained("DedeProGames/GPT-U-20M")
119
+ model = AutoModelForCausalLM.from_pretrained("DedeProGames/GPT-U-20M")
120
+
121
+ inputs = tokenizer("The history of the Roman Empire", return_tensors="pt") # prepends <|endoftext|> as BOS
122
+ output = model.generate(**inputs, max_new_tokens=100, do_sample=True, temperature=0.8, top_p=0.95)
123
+ print(tokenizer.decode(output[0], skip_special_tokens=True))
124
+ ```
125
+
126
+ ## Checkpoints
127
+
128
+ - `main`: final weights (step 19,840, end of the decay phase).
129
+ - [`stable-15872`](https://huggingface.co/DedeProGames/GPT-U-20M/tree/stable-15872): weights at step 15,872, the end of the constant-learning-rate phase, meant for continued pretraining (e.g. extending to 4–5B tokens before decaying again). Load with `revision="stable-15872"`.
130
+
131
+ ## Limitations
132
+
133
+ - **It is tiny.** 20M parameters is a research and teaching scale; the model has shallow world knowledge and weak reasoning.
134
+ - **Heavily over-trained for its size by design:** 127 tokens per parameter, about 6× the Chinchilla-optimal ratio (~20).
135
+ - **Not for production use.** It hallucinates freely and produces fluent but often false statements.
136
+ - **Generated code is not functional.** It imitates the surface form of code; do not run it.
137
+ - English only (web and educational text); no instruction tuning, no safety tuning. Web data can carry biases and offensive content.
138
+ - Context is limited to 1,024 tokens.
139
+
140
+ ## Data provenance and licenses
141
+
142
+ | Source | License | Notes |
143
+ |---|---|---|
144
+ | DCLM-baseline 1.0 | CC-BY-4.0 | Common Crawl web text filtered by DataComp-LM; see the dataset card. |
145
+ | FineWeb-Edu (`sample-10BT`) | ODC-By 1.0 | Common Crawl pages filtered for educational value; use is also subject to Common Crawl's terms of use. |
146
+ | The Stack v3 (train) | ODC-By | GitHub code as of August 2025; files are permissively licensed or carry no detected license (non-permissive files excluded upstream), PII-redacted, with an opt-out process. Individual files keep their original licenses. |
147
+
148
+ The model weights are released under **Apache-2.0**. Tokenized data is not redistributed.
149
+
150
+ ## Reproducibility
151
+
152
+ Everything used to build this model is in the repository: `scripts/` (tokenizer training, data preparation, training, evaluation, publishing), `configs/model.json`, `logs/train.jsonl` (every 10 steps: loss, lr, grad norm, throughput, MFU, GPU temperatures, memory), `logs/tokenizer_report.json` and `out/data_index.json` (token counts per shard and domain, holdout bytes). Raw evaluation outputs: `out/eval.json` and `out/lm_eval_results.json`.
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "LlamaForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 0,
8
+ "dtype": "bfloat16",
9
+ "eos_token_id": 0,
10
+ "head_dim": 64,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 384,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 1024,
15
+ "max_position_embeddings": 1024,
16
+ "mlp_bias": false,
17
+ "model_type": "llama",
18
+ "num_attention_heads": 6,
19
+ "num_hidden_layers": 8,
20
+ "num_key_value_heads": 6,
21
+ "pad_token_id": null,
22
+ "pretraining_tp": 1,
23
+ "rms_norm_eps": 1e-05,
24
+ "rope_parameters": {
25
+ "rope_theta": 10000.0,
26
+ "rope_type": "default"
27
+ },
28
+ "tie_word_embeddings": true,
29
+ "transformers_version": "5.17.0",
30
+ "use_cache": true,
31
+ "vocab_size": 16384
32
+ }
configs/model.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": ["LlamaForCausalLM"],
3
+ "model_type": "llama",
4
+ "vocab_size": 16384,
5
+ "hidden_size": 384,
6
+ "num_hidden_layers": 8,
7
+ "num_attention_heads": 6,
8
+ "num_key_value_heads": 6,
9
+ "head_dim": 64,
10
+ "intermediate_size": 1024,
11
+ "hidden_act": "silu",
12
+ "max_position_embeddings": 1024,
13
+ "rope_theta": 10000.0,
14
+ "rms_norm_eps": 1e-5,
15
+ "tie_word_embeddings": true,
16
+ "attention_bias": false,
17
+ "mlp_bias": false,
18
+ "attention_dropout": 0.0,
19
+ "bos_token_id": 0,
20
+ "eos_token_id": 0,
21
+ "torch_dtype": "bfloat16"
22
+ }
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 0,
3
+ "do_sample": true,
4
+ "eos_token_id": 0,
5
+ "max_new_tokens": 256,
6
+ "pad_token_id": 0,
7
+ "temperature": 0.8,
8
+ "top_p": 0.95,
9
+ "transformers_version": "5.17.0"
10
+ }
logs/tokenizer_report.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "vocab_size": 16384,
3
+ "eot_id": 0,
4
+ "fits_uint16": true,
5
+ "fertility": {
6
+ "dclm": {
7
+ "docs": 1000,
8
+ "tokens": 1310594,
9
+ "tokens_per_word": 1.4774,
10
+ "bytes_per_token": 4.0676
11
+ },
12
+ "edu": {
13
+ "docs": 1000,
14
+ "tokens": 1097829,
15
+ "tokens_per_word": 1.453,
16
+ "bytes_per_token": 4.2398
17
+ },
18
+ "code": {
19
+ "docs": 1000,
20
+ "tokens": 2410115,
21
+ "tokens_per_word": 5.3441,
22
+ "bytes_per_token": 2.0112
23
+ },
24
+ "code_python_only": {
25
+ "docs": 1000,
26
+ "tokens": 1164503,
27
+ "tokens_per_word": 3.7761,
28
+ "bytes_per_token": 3.2095
29
+ }
30
+ },
31
+ "round_trip": {
32
+ "samples": 1000,
33
+ "with_tabs": 151,
34
+ "non_ascii": 730,
35
+ "failures_tokenizers": 0,
36
+ "failures_transformers": 0,
37
+ "first_failures": []
38
+ },
39
+ "example_tokens": [
40
+ "def",
41
+ "Ġf",
42
+ "(x",
43
+ "):Ċ",
44
+ "ĠĠĠĠĠĠĠ",
45
+ "Ġreturn",
46
+ "Ġx",
47
+ "Ċ",
48
+ "ĉ",
49
+ "ĉ",
50
+ "pass",
51
+ "Ġ",
52
+ "Ġ#",
53
+ "Ġ",
54
+ "2",
55
+ "0",
56
+ "2",
57
+ "4"
58
+ ]
59
+ }
logs/train.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd2bd7952b2b22cc121ce27f6c8c533e673a6ada344f47ea4fed5532eec7a97a
3
+ size 40915664
out/data_index.json ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "val": {
3
+ "dclm": {
4
+ "file": "val_dclm.bin",
5
+ "tokens": 2000001,
6
+ "targets": 2000000,
7
+ "docs": 1532,
8
+ "bytes": 8200381,
9
+ "eval_windows": 1600,
10
+ "eval_targets": 1638400,
11
+ "eval_bytes": 6692520,
12
+ "tokens_by_stream": {
13
+ "dclm": 2000952
14
+ },
15
+ "source_files": [
16
+ "global-shard_10_of_10/local-shard_9_of_10/shard_00000278_processed.jsonl.zst"
17
+ ]
18
+ },
19
+ "edu": {
20
+ "file": "val_edu.bin",
21
+ "tokens": 2000001,
22
+ "targets": 2000000,
23
+ "docs": 1825,
24
+ "bytes": 8507401,
25
+ "eval_windows": 1600,
26
+ "eval_targets": 1638400,
27
+ "eval_bytes": 6957806,
28
+ "tokens_by_stream": {
29
+ "edu": 2000602
30
+ },
31
+ "source_files": [
32
+ "sample/10BT/013_00000.parquet"
33
+ ]
34
+ },
35
+ "code": {
36
+ "file": "val_code.bin",
37
+ "tokens": 2000001,
38
+ "targets": 2000000,
39
+ "docs": 807,
40
+ "bytes": 3948091,
41
+ "eval_windows": 1600,
42
+ "eval_targets": 1638400,
43
+ "eval_bytes": 3278661,
44
+ "tokens_by_stream": {
45
+ "code_py": 539515,
46
+ "code_other": 1460486
47
+ },
48
+ "source_files": [
49
+ "data/part-08191-7d88aa48-1310-480e-a9e5-fbbe6a9201cc-c000.snappy.parquet"
50
+ ]
51
+ }
52
+ },
53
+ "tokenizer": "tokenizer/tokenizer.json",
54
+ "dtype": "uint16",
55
+ "seq_len": 1024,
56
+ "block": 1025,
57
+ "stride": 1024,
58
+ "eot_id": 0,
59
+ "seed": 20453760,
60
+ "mix": {
61
+ "method": "each sub-stream tokenized to its token budget, documents interleaved in a seeded random order (per-document sampling at fixed proportions)",
62
+ "target_share_by_stream": {
63
+ "dclm": 0.45,
64
+ "edu": 0.35,
65
+ "code_py": 0.054000000000000006,
66
+ "code_other": 0.146
67
+ },
68
+ "streams": {
69
+ "dclm": {
70
+ "name": "dclm",
71
+ "tokens": 1208022979,
72
+ "docs": 859030,
73
+ "budget": 1208011457,
74
+ "seconds_last_run": 781,
75
+ "tok_s_end_to_end": 1546385,
76
+ "tok_s_tokenizer_capacity": 1844428,
77
+ "num_proc": 4
78
+ },
79
+ "edu": {
80
+ "name": "edu",
81
+ "tokens": 939574378,
82
+ "docs": 826144,
83
+ "budget": 939564467,
84
+ "seconds_last_run": 519,
85
+ "tok_s_end_to_end": 1811732,
86
+ "tok_s_tokenizer_capacity": 1854440,
87
+ "num_proc": 4
88
+ },
89
+ "code_py": {
90
+ "name": "code_py",
91
+ "tokens": 145008215,
92
+ "docs": 123828,
93
+ "budget": 144961375,
94
+ "seconds_last_run": 238,
95
+ "tok_s_end_to_end": 609682,
96
+ "tok_s_tokenizer_capacity": 2510382,
97
+ "num_proc": 4
98
+ },
99
+ "code_other": {
100
+ "name": "code_other",
101
+ "tokens": 391945483,
102
+ "docs": 146176,
103
+ "budget": 391932607,
104
+ "seconds_last_run": 169,
105
+ "tok_s_end_to_end": 2321383,
106
+ "tok_s_tokenizer_capacity": 2684139,
107
+ "num_proc": 4
108
+ }
109
+ },
110
+ "documents_used": {
111
+ "dclm": 858406,
112
+ "edu": 825607,
113
+ "code_py": 123740,
114
+ "code_other": 146076
115
+ }
116
+ },
117
+ "blocks": 2616320,
118
+ "train_steps": 19840,
119
+ "seqs_per_step": 128,
120
+ "margin_steps": 600,
121
+ "shards": [
122
+ {
123
+ "file": "train_000.bin",
124
+ "tokens": 499999745,
125
+ "blocks": 488281,
126
+ "tokens_by_stream": {
127
+ "dclm": 252503253,
128
+ "edu": 186856004,
129
+ "code_py": 27616736,
130
+ "code_other": 33023752
131
+ }
132
+ },
133
+ {
134
+ "file": "train_001.bin",
135
+ "tokens": 499999745,
136
+ "blocks": 488281,
137
+ "tokens_by_stream": {
138
+ "dclm": 173138063,
139
+ "edu": 137035925,
140
+ "code_py": 22360959,
141
+ "code_other": 167464797
142
+ }
143
+ },
144
+ {
145
+ "file": "train_002.bin",
146
+ "tokens": 499999745,
147
+ "blocks": 488281,
148
+ "tokens_by_stream": {
149
+ "dclm": 237113803,
150
+ "edu": 187746379,
151
+ "code_py": 25770365,
152
+ "code_other": 49369197
153
+ }
154
+ },
155
+ {
156
+ "file": "train_003.bin",
157
+ "tokens": 499999745,
158
+ "blocks": 488281,
159
+ "tokens_by_stream": {
160
+ "dclm": 228081435,
161
+ "edu": 176786487,
162
+ "code_py": 30629902,
163
+ "code_other": 64501920
164
+ }
165
+ },
166
+ {
167
+ "file": "train_004.bin",
168
+ "tokens": 499999745,
169
+ "blocks": 488281,
170
+ "tokens_by_stream": {
171
+ "dclm": 228885081,
172
+ "edu": 181806071,
173
+ "code_py": 25343820,
174
+ "code_other": 63964772
175
+ }
176
+ },
177
+ {
178
+ "file": "train_005.bin",
179
+ "tokens": 179112961,
180
+ "blocks": 174915,
181
+ "tokens_by_stream": {
182
+ "dclm": 86984223,
183
+ "edu": 68294576,
184
+ "code_py": 10369458,
185
+ "code_other": 13464703
186
+ }
187
+ }
188
+ ],
189
+ "total": {
190
+ "tokens": 2679111681,
191
+ "tokens_by_stream": {
192
+ "dclm": 1206705858,
193
+ "edu": 938525442,
194
+ "code_py": 142091240,
195
+ "code_other": 391789141
196
+ },
197
+ "tokens_by_domain": {
198
+ "dclm": 1206705858,
199
+ "edu": 938525442,
200
+ "code": 533880381
201
+ },
202
+ "share_by_stream": {
203
+ "dclm": 0.4504126746778945,
204
+ "edu": 0.350312175731953,
205
+ "code_py": 0.053036699069955645,
206
+ "code_other": 0.14623845052019688
207
+ },
208
+ "share_by_domain": {
209
+ "dclm": 0.4504126746778945,
210
+ "edu": 0.350312175731953,
211
+ "code": 0.19927514959015252
212
+ },
213
+ "python_share_of_code": 0.2661480830853007
214
+ },
215
+ "throughput": {
216
+ "tok_s_end_to_end_by_stream": {
217
+ "dclm": 1546385,
218
+ "edu": 1811732,
219
+ "code_py": 609682,
220
+ "code_other": 2321383
221
+ },
222
+ "tok_s_tokenizer_capacity_by_stream": {
223
+ "dclm": 1844428,
224
+ "edu": 1854440,
225
+ "code_py": 2510382,
226
+ "code_other": 2684139
227
+ },
228
+ "num_proc": 4
229
+ }
230
+ }
out/eval.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dclm": {
3
+ "loss": 3.504401680231094,
4
+ "bpb": 1.2377093747792
5
+ },
6
+ "edu": {
7
+ "loss": 3.2586222219467165,
8
+ "bpb": 1.1070218110954395
9
+ },
10
+ "code": {
11
+ "loss": 1.8074918287992476,
12
+ "bpb": 1.3030896824305005
13
+ },
14
+ "aggregate": {
15
+ "loss": 2.8568385769923528,
16
+ "bpb": 1.1966591424256676
17
+ },
18
+ "source": "../out/hf"
19
+ }
out/lm_eval_results.json ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "results": {
3
+ "arc_easy": {
4
+ "name": "arc_easy",
5
+ "alias": "arc_easy",
6
+ "sample_len": 2376,
7
+ "acc,none": 0.40025252525252525,
8
+ "acc_stderr,none": 0.010053550119896153,
9
+ "acc_norm,none": 0.37415824915824913,
10
+ "acc_norm_stderr,none": 0.00992951694897767
11
+ },
12
+ "piqa": {
13
+ "name": "piqa",
14
+ "alias": "piqa",
15
+ "sample_len": 1838,
16
+ "acc,none": 0.5859630032644179,
17
+ "acc_stderr,none": 0.011492118481417717,
18
+ "acc_norm,none": 0.5854189336235038,
19
+ "acc_norm_stderr,none": 0.011494326682255095
20
+ },
21
+ "hellaswag": {
22
+ "name": "hellaswag",
23
+ "alias": "hellaswag",
24
+ "sample_len": 10042,
25
+ "acc,none": 0.26638119896434975,
26
+ "acc_stderr,none": 0.004411624374176628,
27
+ "acc_norm,none": 0.27853017327225654,
28
+ "acc_norm_stderr,none": 0.004473595650807741
29
+ },
30
+ "lambada_openai": {
31
+ "name": "lambada_openai",
32
+ "alias": "lambada_openai",
33
+ "sample_len": 5153,
34
+ "perplexity,none": 138.44775395055893,
35
+ "perplexity_stderr,none": 5.94897318247973,
36
+ "acc,none": 0.217931302154085,
37
+ "acc_stderr,none": 0.005751674912949505
38
+ },
39
+ "winogrande": {
40
+ "name": "winogrande",
41
+ "alias": "winogrande",
42
+ "sample_len": 1267,
43
+ "acc,none": 0.5177584846093133,
44
+ "acc_stderr,none": 0.014043619596174988
45
+ }
46
+ },
47
+ "group_subtasks": {},
48
+ "configs": {
49
+ "arc_easy": {
50
+ "task": "arc_easy",
51
+ "dataset_path": "allenai/ai2_arc",
52
+ "dataset_name": "ARC-Easy",
53
+ "training_split": "train",
54
+ "validation_split": "validation",
55
+ "test_split": "test",
56
+ "doc_to_text": "Question: {{question}}\nAnswer:",
57
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
58
+ "unsafe_code": false,
59
+ "doc_to_choice": "{{choices.text}}",
60
+ "description": "",
61
+ "target_delimiter": " ",
62
+ "fewshot_delimiter": "\n\n",
63
+ "fewshot_config": {
64
+ "sampler": "default",
65
+ "split": null,
66
+ "process_docs": null,
67
+ "fewshot_indices": null,
68
+ "samples": null,
69
+ "doc_to_text": "Question: {{question}}\nAnswer:",
70
+ "doc_to_choice": "{{choices.text}}",
71
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
72
+ "gen_prefix": null,
73
+ "fewshot_delimiter": "\n\n",
74
+ "target_delimiter": " "
75
+ },
76
+ "num_fewshot": 0,
77
+ "metric_list": [
78
+ {
79
+ "metric": "acc",
80
+ "aggregation": "mean",
81
+ "higher_is_better": true
82
+ },
83
+ {
84
+ "metric": "acc_norm",
85
+ "aggregation": "mean",
86
+ "higher_is_better": true
87
+ }
88
+ ],
89
+ "output_type": "multiple_choice",
90
+ "repeats": 1,
91
+ "should_decontaminate": true,
92
+ "doc_to_decontamination_query": "Question: {{question}}\nAnswer:",
93
+ "metadata": {
94
+ "version": 1.0,
95
+ "pretrained": "../out/hf",
96
+ "dtype": "bfloat16",
97
+ "add_bos_token": true,
98
+ "config_source": "/mnt/c/Users/andre/gpt-u-20m-data/pylib/lm_eval/tasks/arc/arc_easy.yaml"
99
+ }
100
+ },
101
+ "hellaswag": {
102
+ "task": "hellaswag",
103
+ "dataset_path": "Rowan/hellaswag",
104
+ "training_split": "train",
105
+ "validation_split": "validation",
106
+ "process_docs": "def process_docs(dataset: datasets.Dataset) -> datasets.Dataset:\n def _process_doc(doc):\n ctx = doc[\"ctx_a\"] + \" \" + doc[\"ctx_b\"].capitalize()\n out_doc = {\n \"query\": preprocess(doc[\"activity_label\"] + \": \" + ctx),\n \"choices\": [preprocess(ending) for ending in doc[\"endings\"]],\n \"gold\": int(doc[\"label\"]),\n }\n return out_doc\n\n return dataset.map(_process_doc)\n",
107
+ "doc_to_text": "{{query}}",
108
+ "doc_to_target": "{{label}}",
109
+ "unsafe_code": false,
110
+ "doc_to_choice": "choices",
111
+ "description": "",
112
+ "target_delimiter": " ",
113
+ "fewshot_delimiter": "\n\n",
114
+ "fewshot_config": {
115
+ "sampler": "default",
116
+ "split": null,
117
+ "process_docs": "<function process_docs at 0x70810087aae0>",
118
+ "fewshot_indices": null,
119
+ "samples": null,
120
+ "doc_to_text": "{{query}}",
121
+ "doc_to_choice": "choices",
122
+ "doc_to_target": "{{label}}",
123
+ "gen_prefix": null,
124
+ "fewshot_delimiter": "\n\n",
125
+ "target_delimiter": " "
126
+ },
127
+ "num_fewshot": 0,
128
+ "metric_list": [
129
+ {
130
+ "metric": "acc",
131
+ "aggregation": "mean",
132
+ "higher_is_better": true
133
+ },
134
+ {
135
+ "metric": "acc_norm",
136
+ "aggregation": "mean",
137
+ "higher_is_better": true
138
+ }
139
+ ],
140
+ "output_type": "multiple_choice",
141
+ "repeats": 1,
142
+ "should_decontaminate": false,
143
+ "metadata": {
144
+ "version": 1.0,
145
+ "pretrained": "../out/hf",
146
+ "dtype": "bfloat16",
147
+ "add_bos_token": true,
148
+ "config_source": "/mnt/c/Users/andre/gpt-u-20m-data/pylib/lm_eval/tasks/hellaswag/hellaswag.yaml"
149
+ }
150
+ },
151
+ "lambada_openai": {
152
+ "task": "lambada_openai",
153
+ "dataset_path": "EleutherAI/lambada_openai",
154
+ "dataset_name": "default",
155
+ "test_split": "test",
156
+ "doc_to_text": "{{text.split(' ')[:-1]|join(' ')}}",
157
+ "doc_to_target": "{{' '+text.split(' ')[-1]}}",
158
+ "unsafe_code": false,
159
+ "description": "",
160
+ "target_delimiter": " ",
161
+ "fewshot_delimiter": "\n\n",
162
+ "fewshot_config": {
163
+ "sampler": "default",
164
+ "split": null,
165
+ "process_docs": null,
166
+ "fewshot_indices": null,
167
+ "samples": null,
168
+ "doc_to_text": "{{text.split(' ')[:-1]|join(' ')}}",
169
+ "doc_to_choice": null,
170
+ "doc_to_target": "{{' '+text.split(' ')[-1]}}",
171
+ "gen_prefix": null,
172
+ "fewshot_delimiter": "\n\n",
173
+ "target_delimiter": " "
174
+ },
175
+ "num_fewshot": 0,
176
+ "metric_list": [
177
+ {
178
+ "metric": "perplexity",
179
+ "aggregation": "perplexity",
180
+ "higher_is_better": false
181
+ },
182
+ {
183
+ "metric": "acc",
184
+ "aggregation": "mean",
185
+ "higher_is_better": true
186
+ }
187
+ ],
188
+ "output_type": "loglikelihood",
189
+ "repeats": 1,
190
+ "should_decontaminate": true,
191
+ "doc_to_decontamination_query": "{{text}}",
192
+ "metadata": {
193
+ "version": 1.0,
194
+ "pretrained": "../out/hf",
195
+ "dtype": "bfloat16",
196
+ "add_bos_token": true,
197
+ "config_source": "/mnt/c/Users/andre/gpt-u-20m-data/pylib/lm_eval/tasks/lambada/lambada_openai.yaml"
198
+ }
199
+ },
200
+ "piqa": {
201
+ "task": "piqa",
202
+ "dataset_path": "baber/piqa",
203
+ "training_split": "train",
204
+ "validation_split": "validation",
205
+ "doc_to_text": "Question: {{goal}}\nAnswer:",
206
+ "doc_to_target": "label",
207
+ "unsafe_code": false,
208
+ "doc_to_choice": "{{[sol1, sol2]}}",
209
+ "description": "",
210
+ "target_delimiter": " ",
211
+ "fewshot_delimiter": "\n\n",
212
+ "fewshot_config": {
213
+ "sampler": "default",
214
+ "split": null,
215
+ "process_docs": null,
216
+ "fewshot_indices": null,
217
+ "samples": null,
218
+ "doc_to_text": "Question: {{goal}}\nAnswer:",
219
+ "doc_to_choice": "{{[sol1, sol2]}}",
220
+ "doc_to_target": "label",
221
+ "gen_prefix": null,
222
+ "fewshot_delimiter": "\n\n",
223
+ "target_delimiter": " "
224
+ },
225
+ "num_fewshot": 0,
226
+ "metric_list": [
227
+ {
228
+ "metric": "acc",
229
+ "aggregation": "mean",
230
+ "higher_is_better": true
231
+ },
232
+ {
233
+ "metric": "acc_norm",
234
+ "aggregation": "mean",
235
+ "higher_is_better": true
236
+ }
237
+ ],
238
+ "output_type": "multiple_choice",
239
+ "repeats": 1,
240
+ "should_decontaminate": true,
241
+ "doc_to_decontamination_query": "goal",
242
+ "metadata": {
243
+ "version": 1.0,
244
+ "pretrained": "../out/hf",
245
+ "dtype": "bfloat16",
246
+ "add_bos_token": true,
247
+ "config_source": "/mnt/c/Users/andre/gpt-u-20m-data/pylib/lm_eval/tasks/piqa/piqa.yaml"
248
+ }
249
+ },
250
+ "winogrande": {
251
+ "task": "winogrande",
252
+ "dataset_path": "allenai/winogrande",
253
+ "dataset_name": "winogrande_xl",
254
+ "training_split": "train",
255
+ "validation_split": "validation",
256
+ "doc_to_text": "def doc_to_text(doc):\n answer_to_num = {\"1\": 0, \"2\": 1}\n return answer_to_num[doc[\"answer\"]]\n",
257
+ "doc_to_target": "def doc_to_target(doc):\n idx = doc[\"sentence\"].index(\"_\") + 1\n return doc[\"sentence\"][idx:].strip()\n",
258
+ "unsafe_code": false,
259
+ "doc_to_choice": "def doc_to_choice(doc):\n idx = doc[\"sentence\"].index(\"_\")\n options = [doc[\"option1\"], doc[\"option2\"]]\n return [doc[\"sentence\"][:idx] + opt for opt in options]\n",
260
+ "description": "",
261
+ "target_delimiter": " ",
262
+ "fewshot_delimiter": "\n\n",
263
+ "fewshot_config": {
264
+ "sampler": "default",
265
+ "split": null,
266
+ "process_docs": null,
267
+ "fewshot_indices": null,
268
+ "samples": null,
269
+ "doc_to_text": "<function doc_to_text at 0x7080d059aa30>",
270
+ "doc_to_choice": "<function doc_to_choice at 0x7080d059a610>",
271
+ "doc_to_target": "<function doc_to_target at 0x7080d059a820>",
272
+ "gen_prefix": null,
273
+ "fewshot_delimiter": "\n\n",
274
+ "target_delimiter": " "
275
+ },
276
+ "num_fewshot": 0,
277
+ "metric_list": [
278
+ {
279
+ "metric": "acc",
280
+ "aggregation": "mean",
281
+ "higher_is_better": true
282
+ }
283
+ ],
284
+ "output_type": "multiple_choice",
285
+ "repeats": 1,
286
+ "should_decontaminate": true,
287
+ "doc_to_decontamination_query": "sentence",
288
+ "metadata": {
289
+ "version": 1.0,
290
+ "pretrained": "../out/hf",
291
+ "dtype": "bfloat16",
292
+ "add_bos_token": true,
293
+ "config_source": "/mnt/c/Users/andre/gpt-u-20m-data/pylib/lm_eval/tasks/winogrande/default.yaml"
294
+ }
295
+ }
296
+ },
297
+ "versions": {
298
+ "arc_easy": 1.0,
299
+ "hellaswag": 1.0,
300
+ "lambada_openai": 1.0,
301
+ "piqa": 1.0,
302
+ "winogrande": 1.0
303
+ },
304
+ "n-shot": {
305
+ "arc_easy": 0,
306
+ "hellaswag": 0,
307
+ "lambada_openai": 0,
308
+ "piqa": 0,
309
+ "winogrande": 0
310
+ },
311
+ "higher_is_better": {
312
+ "arc_easy": {
313
+ "acc": true,
314
+ "acc_norm": true
315
+ },
316
+ "hellaswag": {
317
+ "acc": true,
318
+ "acc_norm": true
319
+ },
320
+ "lambada_openai": {
321
+ "perplexity": false,
322
+ "acc": true
323
+ },
324
+ "piqa": {
325
+ "acc": true,
326
+ "acc_norm": true
327
+ },
328
+ "winogrande": {
329
+ "acc": true
330
+ }
331
+ },
332
+ "n-samples": {
333
+ "arc_easy": {
334
+ "original": 2376,
335
+ "effective": 2376
336
+ },
337
+ "piqa": {
338
+ "original": 1838,
339
+ "effective": 1838
340
+ },
341
+ "hellaswag": {
342
+ "original": 10042,
343
+ "effective": 10042
344
+ },
345
+ "lambada_openai": {
346
+ "original": 5153,
347
+ "effective": 5153
348
+ },
349
+ "winogrande": {
350
+ "original": 1267,
351
+ "effective": 1267
352
+ }
353
+ },
354
+ "config": {
355
+ "model": "hf",
356
+ "model_args": {
357
+ "pretrained": "../out/hf",
358
+ "dtype": "bfloat16",
359
+ "add_bos_token": true
360
+ },
361
+ "model_num_parameters": 20453760,
362
+ "model_dtype": "torch.bfloat16",
363
+ "model_revision": "main",
364
+ "model_sha": "",
365
+ "batch_size": "32",
366
+ "batch_sizes": [],
367
+ "device": "cuda:0",
368
+ "use_cache": null,
369
+ "limit": null,
370
+ "bootstrap_iters": 100000,
371
+ "gen_kwargs": {},
372
+ "random_seed": 0,
373
+ "numpy_seed": 1234,
374
+ "torch_seed": 1234,
375
+ "fewshot_seed": 1234
376
+ },
377
+ "git_hash": null,
378
+ "date": 1790432370.386367,
379
+ "pretty_env_info": "PyTorch version: 2.14.0+cu130\nIs debug build: False\nCUDA used to build PyTorch: 13.0\nROCM used to build PyTorch: N/A\n\nOS: Ubuntu 26.04 LTS (x86_64)\nGCC version: (Ubuntu 15.2.0-16ubuntu1) 15.2.0\nClang version: Could not collect\nCMake version: Could not collect\nLibc version: glibc-2.43\n\nPython version: 3.14.4 (main, Aug 20 2026, 10:41:58) [GCC 15.2.0] (64-bit runtime)\nPython platform: Linux-6.18.33.2-microsoft-standard-WSL2-x86_64-with-glibc2.43\nIs CUDA available: True\nCUDA runtime version: Could not collect\nCUDA_MODULE_LOADING set to: \nGPU models and configuration: \nGPU 0: NVIDIA GeForce RTX 3060\nGPU 1: NVIDIA GeForce RTX 3060\n\nNvidia driver version: 591.86\ncuDNN version: Could not collect\nIs XPU available: False\nHIP runtime version: N/A\nMIOpen runtime version: N/A\nIs XNNPACK available: False\nCaching allocator config: N/A\n\nCPU:\nArchitecture: x86_64\nCPU op-mode(s): 32-bit, 64-bit\nAddress sizes: 39 bits physical, 48 bits virtual\nByte Order: Little Endian\nCPU(s): 6\nOn-line CPU(s) list: 0-5\nVendor ID: GenuineIntel\nModel name: Intel(R) Core(TM) i5-8600K CPU @ 3.60GHz\nCPU family: 6\nModel: 158\nThread(s) per core: 1\nCore(s) per socket: 6\nSocket(s): 1\nStepping: 10\nBogoMIPS: 7199.99\nFlags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm arch_perfmon rep_good nopl xtopology cpuid tsc_known_freq pni pclmulqdq vmx ssse3 fma cx16 pdcm pcid sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch pti ssbd ibrs ibpb stibp tpr_shadow ept vpid ept_ad fsgsbase bmi1 hle avx2 smep bmi2 erms invpcid rtm rdseed adx smap clflushopt xsaveopt xsavec xgetbv1 xsaves vnmi md_clear flush_l1d arch_capabilities\nVirtualization: VT-x\nHypervisor vendor: Microsoft\nVirtualization type: full\nL1d cache: 192 KiB (6 instances)\nL1i cache: 192 KiB (6 instances)\nL2 cache: 1.5 MiB (6 instances)\nL3 cache: 9 MiB (1 instance)\nNUMA node(s): 1\nNUMA node0 CPU(s): 0-5\nVulnerability Gather data sampling: Unknown: Dependent on hypervisor status\nVulnerability Ghostwrite: Not affected\nVulnerability Indirect target selection: Mitigation; Aligned branch/return thunks\nVulnerability Itlb multihit: KVM: Mitigation: VMX disabled\nVulnerability L1tf: Mitigation; PTE Inversion\nVulnerability Mds: Mitigation; Clear CPU buffers; SMT Host state unknown\nVulnerability Meltdown: Mitigation; PTI\nVulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT Host state unknown\nVulnerability Old microcode: Not affected\nVulnerability Reg file data sampling: Not affected\nVulnerability Retbleed: Mitigation; IBRS\nVulnerability Spec rstack overflow: Not affected\nVulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl\nVulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization\nVulnerability Spectre v2: Mitigation; IBRS; IBPB conditional; STIBP disabled; RSB filling; PBRSB-eIBRS Not affected; BHI SW loop, KVM SW loop\nVulnerability Srbds: Unknown: Dependent on hypervisor status\nVulnerability Tsa: Not affected\nVulnerability Tsx async abort: Mitigation; Clear CPU buffers; SMT Host state unknown\nVulnerability Vmscape: Not affected\n\nVersions of relevant libraries:\n[pip3] numpy==2.5.3\n[pip3] nvidia-cublas==13.1.1.3\n[pip3] nvidia-cuda-cupti==13.0.85\n[pip3] nvidia-cuda-nvrtc==13.0.88\n[pip3] nvidia-cuda-runtime==13.0.96\n[pip3] nvidia-cudnn-cu13==9.24.0.43\n[pip3] nvidia-cufft==12.0.0.61\n[pip3] nvidia-curand==10.4.0.35\n[pip3] nvidia-cusolver==12.0.4.66\n[pip3] nvidia-cusparse==12.6.3.3\n[pip3] nvidia-cusparselt-cu13==0.8.1\n[pip3] nvidia-nccl-cu13==2.30.7\n[pip3] nvidia-nvjitlink==13.3.33\n[pip3] nvidia-nvtx==13.0.85\n[pip3] torch==2.14.0+cu130\n[pip3] triton==3.8.0\n[conda] Could not collect",
380
+ "transformers_version": "5.17.0",
381
+ "lm_eval_version": "0.4.13",
382
+ "upper_git_hash": null,
383
+ "tokenizer_pad_token": [
384
+ "<|endoftext|>",
385
+ "0"
386
+ ],
387
+ "tokenizer_eos_token": [
388
+ "<|endoftext|>",
389
+ "0"
390
+ ],
391
+ "tokenizer_bos_token": [
392
+ "<|endoftext|>",
393
+ "0"
394
+ ],
395
+ "eot_token_id": 0,
396
+ "max_length": 1024,
397
+ "task_hashes": {},
398
+ "model_source": "hf",
399
+ "model_name": "../out/hf",
400
+ "model_name_sanitized": "..__out__hf",
401
+ "system_instruction": null,
402
+ "system_instruction_sha": null,
403
+ "fewshot_as_multiturn": null,
404
+ "chat_template": null,
405
+ "chat_template_sha": null,
406
+ "total_evaluation_time_seconds": "567.439990507999"
407
+ }
out/loss.png ADDED

Git LFS Details

  • SHA256: dd3dacff2526d00b9e9422ad1cfecb8b617339eb6493d9fd07fadde57b131a9f
  • Pointer size: 131 Bytes
  • Size of remote file: 166 kB
out/samples.md ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GPT-U-20M samples
2
+
3
+ Sampling: `temperature=0.8`, `top_p=0.95`, `max_new_tokens=200`, seed 0. Each prompt is prefixed with `<|endoftext|>` (the BOS used in training); every sample starts with its prompt.
4
+
5
+ ## Text: `The history of the Roman Empire`
6
+
7
+ ~~~~
8
+ The history of the Roman Empire is not the only one with a history of the Roman Empire. Historians, historians and historians have lived a long and long history of the Roman Empire.
9
+ The history of the Roman Empire is about the Roman Empire. It is about the Roman Empire that was a part of the Roman Empire. The Roman Empire was the Roman Empire, not the Roman Empire. The Romans were the Romans, but they were the people of the world. The Romans were the people of the Roman Empire, and they were the people of the empire. The Romans were the people of the world.
10
+ The history of the Roman Empire includes the Romans, the Roman Empire, the Romans, the Romans and the Roman Empire. The Romans, the Romans and the Roman Empire are similar to the Roman Empire. The Romans and the Romans are the people of the world.
11
+ The history of the Roman Empire is a very interesting and useful account. There are many accounts that are very interesting to look at. Some of the accounts about the
12
+ ~~~~
13
+
14
+ ## Text: `Photosynthesis is the process by which`
15
+
16
+ ~~~~
17
+ Photosynthesis is the process by which plants convert sunlight into nitrogen, which plants are responsible for. These plants are responsible for many of their energy levels, including the amount of sunlight each plant produces.
18
+ The plant’s biosynthesis process is responsible for photosynthesis, which is the process by which plants are used in the production of food for the plant.
19
+ - Cultivation, which is the process by which plants are used to produce the plants.
20
+ - Applied to sunlight in the daytime
21
+ - Under sunlight conditions
22
+ - In the early days of the week
23
+ - In the afternoon
24
+ - In the morning
25
+ - In the middle of the week
26
+ - In the evening
27
+ - In the evening
28
+ - In the evening
29
+ - In the evening
30
+ - In the evening
31
+ - In the evening
32
+ - In the evening
33
+ - In the evening
34
+ - In the evening
35
+ - In the evening
36
+ - In the morning
37
+ - In the evening
38
+ - In the morning
39
+ - In the afternoon
40
+ - In the evening
41
+ ~~~~
42
+
43
+ ## Text: `In a small village near the mountains,`
44
+
45
+ ~~~~
46
+ In a small village near the mountains, the women of Lower England and the rest of the country were singing. The women had not yet been born, but the boys had been born a little past the village in the morning and when they were finished they were born to be the wife of the young woman. The children had a large body of water, and had long and very large hands. The women had their own hands, with no hand that would make a man feel the same way. The boys had a small arms, which was round, round and about half round. The boys had a large head, which was long, very short, with a long, long, long tail. The boys had small arms and a small head, which was very large, which was very short, with long fingers and a short tail. The women had a large head, which was very small, and a large head which was very short. The women had a small head and a large head, which was very long, which was very large
47
+ ~~~~
48
+
49
+ ## Text: `The most important thing to remember when learning a new language is`
50
+
51
+ ~~~~
52
+ The most important thing to remember when learning a new language is understanding which language you’re familiar with. This is because it has a much larger impact on your writing and the language you are learning. Learning a new language can make you feel good in your day to day life and that you will learn what you have learned. This is because it is important to remember what you have learned and it is important to remember what you are learning in this way.
53
+ Here are some tips that you can use to increase your success in your language:
54
+ - Keep up the learning speed. When you are doing this, try to keep your voice heard. This is because it is important to remember when you are learning to be a part of your language. Remember to make sure that you learn to be more conversational and that you can improve your skills in the spoken language.
55
+ - Keep up the learning speed. When you are learning to be a part of a language you will need to be aware of it. You will need to know that you are not a part of a language and
56
+ ~~~~
57
+
58
+ ## Text: `Climate change affects the oceans because`
59
+
60
+ ~~~~
61
+ Climate change affects the oceans because it causes a very high temperature to the oceans. The Earth is warming at a constant rate and it is not going to happen at all.
62
+ Hawaii is a huge landfill and it has a lot of surface and ocean floor land cover. The ocean floor is thick in sand and is covered in sand in some cases. The top layer of soil beneath the rocks is covered in sand, the sea bed, or the ocean floor. The ocean floor of the landfill is covered in sand, which is covered in sand.
63
+ The landfill has very little surface support, so a very high level of surface support is required.
64
+ The water is very high and the water has very little surface support. The water is very low in the atmosphere.
65
+ The rain is very high in the oceans and the oceans are completely dry. The rain is very high in the oceans.
66
+ The oceans are cool because the temperature is high in the atmosphere because the water is cool because it has very little surface support
67
+ ~~~~
68
+
69
+ ## Code: `def fibonacci(n):`
70
+
71
+ ~~~~
72
+ def fibonacci(n):
73
+ if n == 0:
74
+ return 0
75
+ else:
76
+ return n
77
+
78
+ def fibonacci_circular(n):
79
+ if n == 1:
80
+ return 0
81
+ else:
82
+ return 0
83
+
84
+ def fibonacci_circular(n):
85
+ if n == 2:
86
+ return 0
87
+ else:
88
+ return n
89
+
90
+ def fibonacci_circular(n):
91
+ if n == 3:
92
+ return 0
93
+ else:
94
+ return 0
95
+
96
+ def fibonacci_circular(n):
97
+ if n == 4:
98
+ return 0
99
+ else:
100
+ return n
101
+ else:
102
+ return n
103
+
104
+ def fibonacci_circular(n):
105
+ if n == 5:
106
+ return 0
107
+ else:
108
+ return n
109
+
110
+ def fibonacci_circular(n):
111
+ if n == 6:
112
+ return 0
113
+ else:
114
+ return
115
+ ~~~~
116
+
117
+ ## Code: `import numpy as np`
118
+
119
+ ~~~~
120
+ import numpy as np
121
+
122
+
123
+ def normalize(x):
124
+ return np.abs(x) / np.maximum(y) * 2
125
+
126
+ def normalize(x,y):
127
+ return np.maximum(y) * 2
128
+
129
+ def normalize(x,y):
130
+ return np.maximum(y) * 2
131
+
132
+ def normalize(x,y):
133
+ return np.maximum(y) * 2
134
+
135
+ def normalize(x,y):
136
+ return np.abs(x) / (np.maximum(y) * 2)
137
+
138
+
139
+ def normalize(x,y):
140
+ return np.maximum(y) * 2
141
+
142
+ def normalize(x,y):
143
+ return np.abs(x) / (np.maximum(y) * 2)
144
+
145
+
146
+ def normalize(x,y):
147
+ return np.abs(x) / (np.maximum(y) * 2)
148
+
149
+ def normalize(x,y):
150
+ return np.abs(x) / (np.maximum(y) * 2)
151
+
152
+ def normalize(x,y):
153
+ return np.max
154
+ ~~~~
155
+
156
+ ## Code: `class Stack:`
157
+
158
+ ~~~~
159
+ class Stack:
160
+ def __init__(self):
161
+ self.stack = None
162
+ self.stack.extend()
163
+ self.stack.extend()
164
+
165
+ def __str__(self):
166
+ return str(self.stack.extend())
167
+
168
+ ~~~~
169
+
170
+ ## Code: `function debounce(fn, wait) {`
171
+
172
+ ~~~~
173
+ function debounce(fn, wait) {
174
+ fn.enabled = false;
175
+ return fn;
176
+ }
177
+ function debounce(fn, wait) {
178
+ fn.enabled = false;
179
+ }
180
+ function debounce(fn, wait) {
181
+ fn.enabled = false;
182
+ }
183
+ function debounce(fn, wait) {
184
+ fn.enabled = false;
185
+ }
186
+ function debounce(fn, wait) {
187
+ fn.enabled = false;
188
+ }
189
+ function debounce(fn, wait) {
190
+ fn.enabled = false;
191
+ }
192
+ function debounce(fn, wait) {
193
+ fn.enabled = true;
194
+ }
195
+ function debounce(fn, wait) {
196
+ fn.enabled = false;
197
+ }
198
+ function debounce(fn, wait) {
199
+ fn.enabled = false;
200
+ }
201
+ function debounce(fn, wait) {
202
+ fn.enabled = false;
203
+ }
204
+ function debounce(fn, wait) {
205
+ fn.en
206
+ ~~~~
207
+
208
+ ## Code: `#include <stdio.h>`
209
+
210
+ ~~~~
211
+ #include <stdio.h>
212
+
213
+ int main(void) {
214
+ int num = 1000;
215
+ while (num % 2 != 0) {
216
+ cout << num % 2 == 0;
217
+ num += num;
218
+ }
219
+ out.println("\n");
220
+ fprintf("%s\n", num);
221
+ out.println("%s\n", num);
222
+ out.println("\n");
223
+ fprintf("%s\n", num);
224
+ fprintf("%s\n", num);
225
+ out.println("%s\n", num);
226
+ out.println("%s\n", num);
227
+ out.println("%s\n", num);
228
+ out.println("\n");
229
+ fprintf("%s\n", num);
230
+ out.println("%s\n", num);
231
+ out.println("\n");
232
+ fprintf("%s\n", num);
233
+ out.println("\n");
234
+ fprintf("%s\n", num);
235
+ out.println("%s\n", num);
236
+ out.println
237
+ ~~~~
scripts/check_params.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gate: the instantiated model must have exactly 20,453,760 parameters."""
2
+ import math
3
+ import sys
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+
8
+ from common import EXPECTED_PARAMS, build_model
9
+
10
+
11
+ def main() -> int:
12
+ torch.manual_seed(0)
13
+ model = build_model()
14
+ cfg = model.config
15
+ m = model.model
16
+
17
+ total = sum(p.numel() for p in model.parameters())
18
+ emb = m.embed_tokens.weight.numel()
19
+ per_layer = [sum(p.numel() for p in layer.parameters()) for layer in m.layers]
20
+ final_norm = m.norm.weight.numel()
21
+ tied = model.lm_head.weight.data_ptr() == m.embed_tokens.weight.data_ptr()
22
+
23
+ print(f"params total : {total:,}")
24
+ print(f" embedding (tied) : {emb:,}")
25
+ print(f" per layer : {per_layer[0]:,} x {len(per_layer)} = {sum(per_layer):,}")
26
+ print(f" final norm : {final_norm:,}")
27
+ print(f"lm_head tied : {tied}")
28
+ print(f"attn_implementation : {cfg._attn_implementation}")
29
+ print(f"hidden_act : {cfg.hidden_act}")
30
+ print(f"rope : {getattr(cfg, 'rope_parameters', None) or getattr(cfg, 'rope_theta', None)}")
31
+ print(f"param dtype : {next(model.parameters()).dtype}")
32
+
33
+ layer0 = m.layers[0]
34
+ print("init std : "
35
+ f"embed {m.embed_tokens.weight.std():.4f} | q_proj {layer0.self_attn.q_proj.weight.std():.4f} | "
36
+ f"o_proj {layer0.self_attn.o_proj.weight.std():.4f} | gate_proj {layer0.mlp.gate_proj.weight.std():.4f} | "
37
+ f"down_proj {layer0.mlp.down_proj.weight.std():.4f} (target {0.02 / math.sqrt(2 * cfg.num_hidden_layers):.4f}) | "
38
+ f"norm mean {layer0.input_layernorm.weight.mean():.2f}")
39
+
40
+ if torch.cuda.is_available():
41
+ model.cuda()
42
+ x = torch.randint(0, cfg.vocab_size, (4, 1025), device="cuda")
43
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
44
+ logits = model(input_ids=x[:, :-1]).logits
45
+ loss = F.cross_entropy(logits.float().reshape(-1, cfg.vocab_size), x[:, 1:].reshape(-1))
46
+ print(f"init loss (random) : {loss.item():.4f} (ln V = {math.log(cfg.vocab_size):.4f})")
47
+
48
+ ok = total == EXPECTED_PARAMS
49
+ print(f"GATE {'PASS' if ok else 'FAIL'}: {total:,} (esperado {EXPECTED_PARAMS:,})")
50
+ return 0 if ok else 1
51
+
52
+
53
+ if __name__ == "__main__":
54
+ sys.exit(main())
scripts/common.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared helpers for GPT-U-20M: repo paths, model config and model construction."""
2
+ import json
3
+ import math
4
+ from pathlib import Path
5
+
6
+ import torch
7
+ from transformers import LlamaConfig, LlamaForCausalLM
8
+
9
+ ROOT = Path(__file__).resolve().parents[1]
10
+ CONFIG_PATH = ROOT / "configs" / "model.json"
11
+ TOKENIZER_DIR = ROOT / "tokenizer"
12
+ DATA_DIR = ROOT / "data" / "tokens"
13
+ OUT_DIR = ROOT / "out"
14
+ CKPT_DIR = OUT_DIR / "ckpt"
15
+ LOG_DIR = ROOT / "logs"
16
+
17
+ EXPECTED_PARAMS = 20_453_760
18
+ INIT_STD = 0.02
19
+
20
+
21
+ def load_config() -> LlamaConfig:
22
+ return LlamaConfig.from_dict(json.loads(CONFIG_PATH.read_text()), attn_implementation="sdpa")
23
+
24
+
25
+ def init_weights(model: LlamaForCausalLM) -> None:
26
+ """N(0, 0.02) everywhere; residual output projections (o_proj, down_proj) scaled by 1/sqrt(2 * n_layers)."""
27
+ resid_std = INIT_STD / math.sqrt(2 * model.config.num_hidden_layers)
28
+ with torch.no_grad():
29
+ for name, module in model.named_modules():
30
+ if name == "lm_head" and model.config.tie_word_embeddings:
31
+ continue # shares its weight with embed_tokens
32
+ if isinstance(module, torch.nn.Linear):
33
+ module.weight.normal_(0.0, resid_std if name.endswith(("o_proj", "down_proj")) else INIT_STD)
34
+ elif isinstance(module, torch.nn.Embedding):
35
+ module.weight.normal_(0.0, INIT_STD)
36
+ elif type(module).__name__.endswith("RMSNorm"):
37
+ module.weight.fill_(1.0)
38
+
39
+
40
+ def build_model(init: bool = True) -> LlamaForCausalLM:
41
+ # Master weights stay in fp32; bf16 only enters through autocast.
42
+ model = LlamaForCausalLM(load_config()).to(torch.float32)
43
+ if init:
44
+ init_weights(model)
45
+ return model
scripts/evaluate.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GPT-U-20M evaluation: per-domain val loss + bits-per-byte, sample generations, optional lm-eval-harness.
2
+
3
+ python scripts/evaluate.py --ckpt out/ckpt/step_19840.pt # val loss / bpb -> out/eval.json
4
+ python scripts/evaluate.py --hf out/hf --samples # + 10 generations -> out/samples.md
5
+ python scripts/evaluate.py --hf out/hf --lm-eval # benchmarks -> out/lm_eval/
6
+
7
+ bpb = loss_nats * targets / (bytes * ln 2), with the UTF-8 bytes of exactly the evaluated target tokens (index.json).
8
+ """
9
+ import argparse
10
+ import json
11
+ import math
12
+ import subprocess
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import torch
18
+ import torch.distributed as dist
19
+ import torch.nn.functional as F
20
+
21
+ from common import CKPT_DIR, DATA_DIR, OUT_DIR, TOKENIZER_DIR, build_model
22
+
23
+ SEQ = 1024
24
+ EVAL_BATCH = 8 # 200 batches x 8 sequences = the 1,600 fixed windows of each holdout
25
+ EOT_ID = 0
26
+ LM_EVAL_TASKS = "arc_easy,piqa,hellaswag,lambada_openai,winogrande"
27
+ TEXT_PROMPTS = [
28
+ "The history of the Roman Empire",
29
+ "Photosynthesis is the process by which",
30
+ "In a small village near the mountains,",
31
+ "The most important thing to remember when learning a new language is",
32
+ "Climate change affects the oceans because",
33
+ ]
34
+ CODE_PROMPTS = [
35
+ "def fibonacci(n):\n",
36
+ "import numpy as np\n\n\ndef normalize(x):\n",
37
+ "class Stack:\n def __init__(self):\n",
38
+ "function debounce(fn, wait) {\n",
39
+ "#include <stdio.h>\n\nint main(void) {\n",
40
+ ]
41
+
42
+
43
+ @torch.no_grad()
44
+ def val_losses(model: torch.nn.Module, device: torch.device, rank: int = 0, world: int = 1) -> dict:
45
+ """Val loss and bits-per-byte on each holdout; windows are split across ranks and the sums all-reduced."""
46
+ val = json.loads((DATA_DIR / "index.json").read_text())["val"]
47
+ was_training = model.training
48
+ model.eval()
49
+ results, nats_all, targets_all, bytes_all = {}, 0.0, 0.0, 0
50
+ for domain, v in val.items():
51
+ arr = np.fromfile(DATA_DIR / v["file"], dtype=np.uint16) # 4 MB; avoids mmap over DrvFs
52
+ windows = np.arange(v["eval_windows"])[rank::world]
53
+ acc = torch.zeros(2, dtype=torch.float64, device=device)
54
+ for i in range(0, len(windows), EVAL_BATCH):
55
+ rows = np.stack([arr[k * SEQ:k * SEQ + SEQ + 1] for k in windows[i:i + EVAL_BATCH]]).astype(np.int64)
56
+ x = torch.from_numpy(rows).to(device)
57
+ with torch.autocast("cuda", dtype=torch.bfloat16):
58
+ logits = model(input_ids=x[:, :-1], use_cache=False).logits
59
+ acc[0] += F.cross_entropy(logits.float().flatten(0, 1), x[:, 1:].flatten(), reduction="sum").double()
60
+ acc[1] += x[:, 1:].numel()
61
+ if world > 1:
62
+ dist.all_reduce(acc)
63
+ nats, targets = acc.tolist()
64
+ assert int(targets) == v["eval_targets"], f"{domain}: evaluated {targets} targets"
65
+ results[domain] = {"loss": nats / targets, "bpb": nats / (v["eval_bytes"] * math.log(2))}
66
+ nats_all, targets_all, bytes_all = nats_all + nats, targets_all + targets, bytes_all + v["eval_bytes"]
67
+ results["aggregate"] = {"loss": nats_all / targets_all, "bpb": nats_all / (bytes_all * math.log(2))}
68
+ model.train(was_training)
69
+ return results
70
+
71
+
72
+ def load_model(ckpt: Path | None, hf_dir: Path | None, device: torch.device):
73
+ if hf_dir:
74
+ from transformers import AutoModelForCausalLM
75
+ return AutoModelForCausalLM.from_pretrained(hf_dir, dtype=torch.float32).to(device)
76
+ model = build_model(init=False)
77
+ model.load_state_dict(torch.load(ckpt, map_location="cpu", weights_only=False)["model"])
78
+ return model.to(device)
79
+
80
+
81
+ @torch.no_grad()
82
+ def write_samples(model, device: torch.device, path: Path) -> None:
83
+ from transformers import AutoTokenizer
84
+ tok = AutoTokenizer.from_pretrained(TOKENIZER_DIR)
85
+ torch.manual_seed(0)
86
+ lines = ["# GPT-U-20M samples", "",
87
+ "Sampling: `temperature=0.8`, `top_p=0.95`, `max_new_tokens=200`, seed 0. "
88
+ "Each prompt is prefixed with `<|endoftext|>` (the BOS used in training); every sample starts with its prompt.", ""]
89
+ model.eval()
90
+ for kind, prompts in (("Text", TEXT_PROMPTS), ("Code", CODE_PROMPTS)):
91
+ for prompt in prompts:
92
+ ids = torch.tensor([[EOT_ID] + tok.encode(prompt, add_special_tokens=False)], device=device)
93
+ with torch.autocast("cuda", dtype=torch.bfloat16):
94
+ out = model.generate(ids, do_sample=True, temperature=0.8, top_p=0.95, max_new_tokens=200,
95
+ eos_token_id=EOT_ID, pad_token_id=EOT_ID)
96
+ completion = tok.decode(out[0, ids.shape[1]:], skip_special_tokens=True)
97
+ title = prompt.strip().splitlines()[0]
98
+ lines += [f"## {kind}: `{title}`", "", "~~~~", prompt + completion, "~~~~", ""]
99
+ path.write_text("\n".join(lines), encoding="utf-8")
100
+
101
+
102
+ def run_lm_eval(hf_dir: Path, out_dir: Path) -> None:
103
+ subprocess.run([sys.executable, "-m", "lm_eval", "--model", "hf",
104
+ "--model_args", f"pretrained={hf_dir},dtype=bfloat16,add_bos_token=True", "--tasks", LM_EVAL_TASKS,
105
+ "--batch_size", "32", "--output_path", str(out_dir)], check=True)
106
+
107
+
108
+ def main() -> None:
109
+ ap = argparse.ArgumentParser()
110
+ ap.add_argument("--ckpt", type=Path, help="training checkpoint (default: newest in out/ckpt)")
111
+ ap.add_argument("--hf", type=Path, help="exported Hugging Face model directory")
112
+ ap.add_argument("--samples", action="store_true")
113
+ ap.add_argument("--lm-eval", action="store_true")
114
+ args = ap.parse_args()
115
+ device = torch.device("cuda", 0)
116
+ ckpt = args.ckpt or (None if args.hf else sorted(CKPT_DIR.glob("step_*.pt"))[-1])
117
+ model = load_model(ckpt, args.hf, device)
118
+
119
+ results = val_losses(model, device)
120
+ results["source"] = str(args.hf or ckpt)
121
+ (OUT_DIR / "eval.json").write_text(json.dumps(results, indent=2))
122
+ print(json.dumps(results, indent=2))
123
+ if args.samples:
124
+ write_samples(model, device, OUT_DIR / "samples.md")
125
+ if args.lm_eval:
126
+ run_lm_eval(args.hf, OUT_DIR / "lm_eval")
127
+
128
+
129
+ if __name__ == "__main__":
130
+ main()
scripts/hwmon.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Append GPU temperature / power / utilization, CPU load and WSL memory / swap use every 5 s to a CSV on the
3
+ # Windows drive, which keeps its last lines through a sudden crash better than the WSL virtual disk.
4
+ OUT=${1:-/mnt/c/Users/andre/AppData/Local/Temp/gptu_hwmon2.csv}
5
+ [ -f "$OUT" ] || echo "time,gpu0_temp,gpu0_power_w,gpu0_util,gpu1_temp,gpu1_power_w,gpu1_util,load1,mem_used_mb,swap_used_mb" > "$OUT"
6
+ while true; do
7
+ g=$(nvidia-smi --query-gpu=temperature.gpu,power.draw,utilization.gpu --format=csv,noheader,nounits | tr -d ' ' | paste -sd, -)
8
+ m=$(free -m | awk '/^Mem:/{u=$3} /^Swap:/{s=$3} END{print u","s}')
9
+ echo "$(date +%FT%T),$g,$(cut -d' ' -f1 /proc/loadavg),$m" >> "$OUT"
10
+ sleep 5
11
+ done
scripts/plot.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Loss curve for GPT-U-20M: training loss (logged value + 100-step mean) and validation loss per domain."""
2
+ import json
3
+ from pathlib import Path
4
+
5
+ import matplotlib
6
+
7
+ matplotlib.use("Agg")
8
+ import matplotlib.pyplot as plt
9
+
10
+ SURFACE, INK, INK_2, MUTED, GRID, AXIS = "#fcfcfb", "#0b0b0b", "#52514e", "#898781", "#e1e0d9", "#c3c2b7"
11
+ DOMAIN_COLORS = {"dclm": "#2a78d6", "edu": "#eb6834", "code": "#1baf7a"} # categorical slots 1-3, fixed order
12
+ PHASES = ((500, "warmup ends"), (15_872, "decay starts"))
13
+
14
+
15
+ def read_log(path: Path) -> tuple[list, list]:
16
+ """Last record per step wins (a resumed run re-logs the steps after its checkpoint)."""
17
+ train, evals = {}, {}
18
+ for line in path.read_text(encoding="utf-8").splitlines():
19
+ rec = json.loads(line)
20
+ if rec.get("event") == "eval":
21
+ evals[rec["step"]] = rec
22
+ elif "event" not in rec:
23
+ train[rec["step"]] = rec["loss"]
24
+ return sorted(train.items()), sorted(evals.items())
25
+
26
+
27
+ def _style(ax, title: str, ylabel: str) -> None:
28
+ ax.set_facecolor(SURFACE)
29
+ ax.set_title(title, loc="left", color=INK, fontsize=11)
30
+ ax.set_xlabel("step (131,072 tokens each)", color=INK_2, fontsize=9)
31
+ ax.set_ylabel(ylabel, color=INK_2, fontsize=9)
32
+ ax.grid(axis="y", color=GRID, linewidth=0.5)
33
+ ax.set_axisbelow(True)
34
+ for side in ("top", "right"):
35
+ ax.spines[side].set_visible(False)
36
+ for side in ("left", "bottom"):
37
+ ax.spines[side].set_color(AXIS)
38
+ ax.tick_params(colors=MUTED, labelsize=8)
39
+
40
+
41
+ def _phase_lines(ax, x_max: int) -> None:
42
+ for step, label in PHASES:
43
+ if step <= x_max:
44
+ ax.axvline(step, color=AXIS, linewidth=0.6, linestyle=(0, (3, 3)))
45
+ ax.annotate(label, (step, 1), xycoords=("data", "axes fraction"), xytext=(3, -10),
46
+ textcoords="offset points", color=MUTED, fontsize=7)
47
+
48
+
49
+ def plot_loss(log_path: Path, out_path: Path, total_steps: int) -> None:
50
+ train, evals = read_log(Path(log_path))
51
+ fig, (ax_t, ax_v) = plt.subplots(1, 2, figsize=(12, 4.6), dpi=150, facecolor=SURFACE)
52
+ _style(ax_t, "Training loss", "cross-entropy (nats/token)")
53
+ _style(ax_v, "Validation loss by domain", "cross-entropy (nats/token)")
54
+ x_max = max([s for s, _ in train] + [s for s, _ in evals] + [1])
55
+
56
+ if train:
57
+ steps, loss = zip(*train)
58
+ window = 10 # log points are 10 steps apart -> 100-step mean
59
+ mean = [sum(loss[max(0, i - window + 1):i + 1]) / len(loss[max(0, i - window + 1):i + 1]) for i in range(len(loss))]
60
+ ax_t.plot(steps, loss, color=AXIS, linewidth=0.6, label="logged loss")
61
+ ax_t.plot(steps, mean, color=INK, linewidth=1.2, label="100-step mean")
62
+ settled = [l for s, l in train if s >= min(300, steps[-1] // 5)] or list(loss)
63
+ ax_t.set_ylim(min(loss) - 0.15, max(settled) + 0.3)
64
+ ax_t.annotate(f"{mean[-1]:.3f}", (steps[-1], mean[-1]), xytext=(4, 0), textcoords="offset points",
65
+ color=INK_2, fontsize=8, va="center")
66
+ if steps[0] <= 10:
67
+ ax_t.text(0.01, 0.02, f"step {steps[0]} loss {loss[0]:.2f} (off scale)", transform=ax_t.transAxes,
68
+ ha="left", va="bottom", color=MUTED, fontsize=7)
69
+ ax_t.legend(loc="upper right", bbox_to_anchor=(1, 0.92), frameon=False, fontsize=8, labelcolor=INK_2)
70
+
71
+ if evals:
72
+ ends = []
73
+ for domain, color in DOMAIN_COLORS.items():
74
+ pts = [(s, r[domain]["loss"]) for s, r in evals if domain in r]
75
+ if pts:
76
+ xs, ys = zip(*pts)
77
+ ax_v.plot(xs, ys, color=color, linewidth=1.2, marker="o", markersize=4.5,
78
+ markeredgecolor=SURFACE, markeredgewidth=1, label=domain)
79
+ ends.append([ys[-1], domain, xs[-1], ys[-1]])
80
+ lo, hi = ax_v.get_ylim()
81
+ gap = (hi - lo) * 0.06 # dodge direct labels that would collide
82
+ ends.sort()
83
+ for i in range(1, len(ends)):
84
+ ends[i][0] = max(ends[i][0], ends[i - 1][0] + gap)
85
+ for label_y, domain, x, last in ends:
86
+ ax_v.annotate(f"{domain} {last:.3f}", (x, label_y), xytext=(6, 0), textcoords="offset points",
87
+ color=INK_2, fontsize=8, va="center")
88
+ ax_v.legend(loc="upper center", frameon=False, fontsize=8, labelcolor=INK_2)
89
+ else:
90
+ ax_v.text(0.5, 0.5, "no evaluation yet", transform=ax_v.transAxes, ha="center", color=MUTED)
91
+
92
+ for ax in (ax_t, ax_v):
93
+ ax.set_xlim(0, max(x_max * 1.08, 10))
94
+ _phase_lines(ax, x_max)
95
+ fig.suptitle(f"GPT-U-20M · step {x_max:,} / {total_steps:,}", x=0.01, ha="left", color=INK_2, fontsize=9)
96
+ fig.tight_layout()
97
+ out_path.parent.mkdir(parents=True, exist_ok=True)
98
+ tmp = out_path.with_suffix(".tmp.png")
99
+ fig.savefig(tmp, facecolor=SURFACE)
100
+ plt.close(fig)
101
+ tmp.replace(out_path)
scripts/prepare_data.py ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the GPT-U-20M token shards: 2.68B tokens of the 45/35/20 mix plus 2M-token holdouts per domain.
2
+
3
+ Stages (each resumable; run through scripts/run_prepare.sh, which restarts the process between stages):
4
+ 1. holdout data/tokens/val_<domain>.bin from holdout source files that never feed training or the tokenizer
5
+ 2. streams each sub-stream (dclm, edu, code_py, code_other) is streamed from the Hub on its own and tokenized
6
+ until its token budget (share x total, +0.2% slack) -> data/tokens/streams/<name>.bin
7
+ 3. assemble documents of the four stream files are interleaved in a seeded random order -> train_XXX.bin
8
+ 4. validate sizes, token ids, shard overlaps, holdouts; then the stream files are deleted
9
+
10
+ Why streams are tokenized one at a time: holding the four Hub streams open together needs 7-8 GB with spikes past
11
+ 11 GB, and on this machine memory pressure plus disk I/O has bugchecked Windows. One stream at a time peaks at ~2.5 GB.
12
+ The interleave is still per document with proportions fixed for the whole run (a seeded permutation of all documents),
13
+ so there are no domain blocks, and because every stream holds exactly its token share the realized shares are exact.
14
+
15
+ Shard format: uint16 token stream; every document is prefixed with <|endoftext|> (id 0); no padding, nothing
16
+ truncated. Shard k holds blocks*1024+1 tokens and its last token is repeated as the first token of shard k+1, so
17
+ block j of a shard is tokens[j*1024 : j*1024+1025].
18
+ """
19
+ import argparse
20
+ import copy
21
+ import json
22
+ import multiprocessing as mp
23
+ import os
24
+ import random
25
+ import sys
26
+ import threading
27
+ import time
28
+ from pathlib import Path
29
+
30
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") # parallelism comes from the process pool
31
+ os.environ.setdefault("ARROW_DEFAULT_MEMORY_POOL", "system") # glibc malloc gives arrow buffers back; jemalloc hoards
32
+
33
+ import numpy as np
34
+ from tokenizers import Tokenizer
35
+
36
+ from sources import SEED, STREAM_DOMAIN, STREAM_SHARE, STREAMS, file_splits, open_stream
37
+
38
+ ROOT = Path(__file__).resolve().parents[1]
39
+ TOKENIZER_PATH = ROOT / "tokenizer" / "tokenizer.json"
40
+ SPLITS_PATH = ROOT / "data" / "file_splits.json"
41
+ VAL_DIR = ROOT / "data" / "tokens"
42
+
43
+ SEQ = 1024
44
+ STEPS, SEQS_PER_STEP = 19_840, 128
45
+ MARGIN_STEPS = 3 * 200 # room for the NaN guard's data skips (max 3 events x 200 steps) without repeating data
46
+ FULL_BLOCKS = (STEPS + MARGIN_STEPS) * SEQS_PER_STEP
47
+ STREAM_SLACK = 1.002 # each stream collects 0.2% over its share so assembly never runs short
48
+ HOLDOUT_TOKENS = 2_000_000
49
+ EVAL_WINDOWS = 200 * 8 # evaluate.py: 200 batches x 8 sequences
50
+ BATCH_DOCS = 512
51
+ BATCH_CHARS = 8_000_000 # also cap a batch by size: a few huge code files must not balloon a tokenizer worker
52
+ CKPT_EVERY = 20_000_000
53
+ READ_CHUNK = 16_000_000 # tokens per sequential read while assembling (DrvFs-friendly)
54
+ NUM_PROC = max(1, (os.cpu_count() or 3) - 2)
55
+ EOT_ID = 0
56
+ DOMAINS = ("dclm", "edu", "code")
57
+ SRC_IDX = {name: i for i, name in enumerate(STREAMS)}
58
+ RESTART_EXIT_CODE = 75 # run_prepare.sh starts a fresh process: next stage, or resume after the memory guard
59
+ MIN_AVAILABLE_GB = 3.0 # checked after every batch: checkpoint, then restart
60
+ HARD_MIN_AVAILABLE_GB = 1.5 # checked twice a second: restart at once from the last periodic checkpoint
61
+
62
+
63
+ def log(msg: str) -> None:
64
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
65
+
66
+
67
+ def write_json(path: Path, obj: dict) -> None:
68
+ tmp = path.with_suffix(path.suffix + ".tmp")
69
+ tmp.write_text(json.dumps(obj, indent=2))
70
+ os.replace(tmp, path)
71
+
72
+
73
+ def load_tokenizer() -> Tokenizer:
74
+ tok = Tokenizer.from_file(str(TOKENIZER_PATH))
75
+ tok.encode_special_tokens = True # a literal "<|endoftext|>" inside a document is plain text
76
+ return tok
77
+
78
+
79
+ # ---------------------------------------------------------------- memory guard
80
+ def rss_gb(pid: int | str = "self") -> float:
81
+ try:
82
+ with open(f"/proc/{pid}/status") as f:
83
+ return next(int(line.split()[1]) for line in f if line.startswith("VmRSS")) / 2**20
84
+ except (OSError, StopIteration): # the process is gone
85
+ return 0.0
86
+
87
+
88
+ def tree_rss_gb() -> float:
89
+ """This process plus its tokenizer workers."""
90
+ return rss_gb() + sum(rss_gb(child.pid) for child in mp.active_children())
91
+
92
+
93
+ def available_gb() -> float:
94
+ with open("/proc/meminfo") as f:
95
+ return next(int(line.split()[1]) for line in f if line.startswith("MemAvailable")) / 2**20
96
+
97
+
98
+ def start_memory_watchdog() -> None:
99
+ """Last line of defence for spikes between batch checks (or during a resume's fast-forward, which writes
100
+ nothing): kill the workers and exit at once; the restart redoes at most CKPT_EVERY tokens."""
101
+
102
+ def watch() -> None:
103
+ while True:
104
+ available = available_gb()
105
+ if available < HARD_MIN_AVAILABLE_GB:
106
+ log(f"memory watchdog: WSL available {available:.2f} GB -> hard restart from the last checkpoint")
107
+ for child in mp.active_children():
108
+ child.kill()
109
+ sys.stdout.flush()
110
+ os._exit(RESTART_EXIT_CODE)
111
+ time.sleep(0.5)
112
+
113
+ threading.Thread(target=watch, daemon=True, name="memory-watchdog").start()
114
+
115
+
116
+ # ---------------------------------------------------------------- tokenizer workers (spawned processes)
117
+ _tok = None
118
+
119
+
120
+ def _init_worker() -> None:
121
+ global _tok
122
+ _tok = load_tokenizer()
123
+
124
+
125
+ def _encode(job):
126
+ b, texts = job
127
+ t0 = time.perf_counter()
128
+ encs = _tok.encode_batch_fast(texts)
129
+ lens = np.fromiter((len(e.ids) + 1 for e in encs), dtype=np.int64, count=len(encs))
130
+ ids = np.empty(int(lens.sum()), dtype=np.uint16)
131
+ pos = 0
132
+ for e, n in zip(encs, lens):
133
+ ids[pos] = EOT_ID
134
+ ids[pos + 1:pos + n] = e.ids
135
+ pos += n
136
+ return b, ids, lens, time.perf_counter() - t0
137
+
138
+
139
+ # ---------------------------------------------------------------- 1. holdout
140
+ def token_byte_lengths(tok: Tokenizer) -> np.ndarray:
141
+ """UTF-8 bytes per token id. Each byte-level BPE character stands for exactly one byte; the special token is 0."""
142
+ lengths = np.zeros(tok.get_vocab_size(), dtype=np.int64)
143
+ for token, idx in tok.get_vocab().items():
144
+ if idx != EOT_ID:
145
+ lengths[idx] = len(token)
146
+ return lengths
147
+
148
+
149
+ def build_holdout(splits: dict, tok: Tokenizer) -> dict:
150
+ """2M tokens per domain from the holdout files; the code holdout holds the same 27/73 Python split as training."""
151
+ VAL_DIR.mkdir(parents=True, exist_ok=True)
152
+ byte_len = token_byte_lengths(tok)
153
+ index_path = VAL_DIR / "index.json"
154
+ val = json.loads(index_path.read_text()).get("val", {}) if index_path.exists() else {}
155
+ need = HOLDOUT_TOKENS + 1
156
+ for domain in DOMAINS:
157
+ path = VAL_DIR / f"val_{domain}.bin"
158
+ if domain in val and path.exists():
159
+ continue
160
+ names = [n for n in STREAMS if STREAM_DOMAIN[n] == domain]
161
+ docs = []
162
+ for name in names:
163
+ budget = need * STREAM_SHARE[name] / sum(STREAM_SHARE[n] for n in names)
164
+ got = 0
165
+ for row in open_stream(name, splits[domain]["holdout"]):
166
+ ids = np.array([EOT_ID] + tok.encode(row["text"]).ids, dtype=np.uint16)
167
+ docs.append((name, ids))
168
+ got += len(ids)
169
+ if got >= budget:
170
+ break
171
+ random.Random(SEED).shuffle(docs)
172
+ chunks, by_stream, n = [], dict.fromkeys(names, 0), 0
173
+ for name, ids in docs:
174
+ take = min(len(ids), need - n)
175
+ chunks.append(ids[:take])
176
+ by_stream[name] += take
177
+ n += take
178
+ if n == need:
179
+ break
180
+ arr = np.concatenate(chunks)
181
+ assert len(arr) == need, f"holdout {domain}: only {len(arr):,} tokens"
182
+ targets = arr[1:]
183
+ tmp = path.with_suffix(".bin.tmp")
184
+ arr.tofile(tmp)
185
+ os.replace(tmp, path)
186
+ val[domain] = {
187
+ "file": path.name, "tokens": int(len(arr)), "targets": int(len(targets)), "docs": len(chunks),
188
+ "bytes": int(byte_len[targets].sum()),
189
+ "eval_windows": EVAL_WINDOWS, "eval_targets": EVAL_WINDOWS * SEQ,
190
+ "eval_bytes": int(byte_len[targets[:EVAL_WINDOWS * SEQ]].sum()),
191
+ "tokens_by_stream": by_stream, "source_files": splits[domain]["holdout"],
192
+ }
193
+ log(f"holdout {domain}: {len(arr):,} tokens, {len(chunks):,} docs, {val[domain]['bytes']:,} bytes "
194
+ f"({val[domain]['bytes'] / len(targets):.3f} bytes/token), by stream {by_stream}")
195
+ index = json.loads(index_path.read_text()) if index_path.exists() else {}
196
+ index["val"] = val
197
+ write_json(index_path, index)
198
+ return val
199
+
200
+
201
+ # ---------------------------------------------------------------- 2. one sub-stream -> token file
202
+ def tokenize_stream(name: str, files: list[str], budget: int, max_rss_gb: float, stream_dir: Path) -> dict:
203
+ """Stream one sub-stream from the Hub and append its EOT-prefixed documents to <stream_dir>/<name>.bin until the
204
+ token budget is reached (whole documents only). Checkpoints every CKPT_EVERY tokens."""
205
+ stream_dir.mkdir(parents=True, exist_ok=True)
206
+ out_path, meta_path = stream_dir / f"{name}.bin", stream_dir / f"{name}.json"
207
+ tmp_path, ckpt_path = stream_dir / f"{name}.bin.tmp", stream_dir / f"{name}.state.json"
208
+ state = json.loads(ckpt_path.read_text()) if ckpt_path.exists() else None
209
+ ds = open_stream(name, files)
210
+ if state:
211
+ ds.load_state_dict(state["stream"])
212
+ tokens, docs = (state["tokens"], state["docs"]) if state else (0, 0)
213
+ f = open(tmp_path, "r+b" if state and tmp_path.exists() else "wb")
214
+ f.truncate(tokens * 2)
215
+ f.seek(tokens * 2)
216
+ log(f"{name}: budget {budget / 1e6:,.1f}M tokens" + (f", resuming at {tokens / 1e6:,.1f}M" if state else ""))
217
+
218
+ stop = threading.Event()
219
+ sem = threading.Semaphore(2 * NUM_PROC) # keeps the pool from pulling the whole stream into memory
220
+ stream_states = {}
221
+
222
+ def jobs():
223
+ texts, n_chars, b = [], 0, 0
224
+ for row in ds:
225
+ if not row["text"]:
226
+ continue
227
+ texts.append(row["text"])
228
+ n_chars += len(row["text"])
229
+ if len(texts) == BATCH_DOCS or n_chars >= BATCH_CHARS:
230
+ sem.acquire()
231
+ if stop.is_set():
232
+ return
233
+ stream_states[b] = copy.deepcopy(ds.state_dict())
234
+ yield b, texts
235
+ texts, n_chars, b = [], 0, b + 1
236
+
237
+ def checkpoint(stream_state: dict) -> None:
238
+ f.flush()
239
+ os.fsync(f.fileno())
240
+ write_json(ckpt_path, {"stream": stream_state, "tokens": tokens, "docs": docs})
241
+
242
+ start_tokens, enc_secs, t0 = tokens, 0.0, time.time()
243
+ next_ckpt, next_log = tokens + CKPT_EVERY, tokens + 100_000_000
244
+ done = False
245
+ with mp.get_context("spawn").Pool(NUM_PROC, initializer=_init_worker) as pool:
246
+ for b, ids, lens, secs in pool.imap(_encode, jobs()):
247
+ sem.release()
248
+ stream_state = stream_states.pop(b)
249
+ if tokens + ids.size >= budget: # stop after the document that crosses the budget
250
+ cut = int(np.searchsorted(np.cumsum(lens), budget - tokens)) + 1
251
+ ids, lens = ids[:int(lens[:cut].sum())], lens[:cut]
252
+ done = True
253
+ f.write(ids.tobytes())
254
+ tokens += int(ids.size)
255
+ docs += len(lens)
256
+ enc_secs += secs
257
+ if done:
258
+ break
259
+ if tokens >= next_ckpt:
260
+ checkpoint(stream_state)
261
+ next_ckpt += CKPT_EVERY
262
+ if tree_rss_gb() > max_rss_gb or available_gb() < MIN_AVAILABLE_GB:
263
+ checkpoint(stream_state)
264
+ log(f"memory guard: prep rss {tree_rss_gb():.1f} GB, WSL available {available_gb():.1f} GB at "
265
+ f"{tokens / 1e6:,.0f}M {name} tokens -> checkpoint written, restarting")
266
+ stop.set()
267
+ for _ in range(4 * NUM_PROC):
268
+ sem.release()
269
+ pool.terminate()
270
+ sys.stdout.flush()
271
+ os._exit(RESTART_EXIT_CODE) # streaming threads can stall a normal interpreter exit
272
+ if tokens >= next_log:
273
+ rate = (tokens - start_tokens) / (time.time() - t0)
274
+ log(f"{name}: {tokens / 1e6:,.0f}M / {budget / 1e6:,.0f}M tokens | {rate:,.0f} tok/s end-to-end | "
275
+ f"tokenizer capacity {(tokens - start_tokens) / enc_secs * NUM_PROC:,.0f} tok/s | "
276
+ f"ETA {(budget - tokens) / rate / 60:.0f} min | prep rss {tree_rss_gb():.1f} GB")
277
+ next_log += 100_000_000
278
+ stop.set()
279
+ for _ in range(4 * NUM_PROC):
280
+ sem.release()
281
+ pool.terminate()
282
+ if not done:
283
+ raise RuntimeError(f"{name}: source files ran out at {tokens:,} tokens (budget {budget:,})")
284
+
285
+ f.flush()
286
+ os.fsync(f.fileno())
287
+ f.close()
288
+ os.replace(tmp_path, out_path)
289
+ secs = time.time() - t0
290
+ meta = {"name": name, "tokens": tokens, "docs": docs, "budget": budget, "seconds_last_run": round(secs),
291
+ "tok_s_end_to_end": round((tokens - start_tokens) / secs),
292
+ "tok_s_tokenizer_capacity": round((tokens - start_tokens) / enc_secs * NUM_PROC), "num_proc": NUM_PROC}
293
+ write_json(meta_path, meta)
294
+ ckpt_path.unlink(missing_ok=True)
295
+ log(f"{name}: done, {tokens:,} tokens, {docs:,} docs, {meta['tok_s_end_to_end']:,} tok/s end-to-end, "
296
+ f"tokenizer capacity {meta['tok_s_tokenizer_capacity']:,} tok/s")
297
+ return meta
298
+
299
+
300
+ # ---------------------------------------------------------------- 3. assemble shards
301
+ class ShardWriter:
302
+ def __init__(self, out_dir: Path, total_blocks: int, shard_tokens: int):
303
+ self.out_dir = out_dir
304
+ self.total_blocks = total_blocks
305
+ self.shard_blocks = shard_tokens // SEQ
306
+ self.shards = []
307
+ self.blocks_done = 0
308
+ self.cur = 0
309
+ self.cur_counts = np.zeros(len(STREAMS), dtype=np.int64)
310
+ self._open()
311
+
312
+ def _target(self) -> tuple[int, int]:
313
+ blocks = min(self.shard_blocks, self.total_blocks - self.blocks_done)
314
+ return blocks, blocks * SEQ + 1
315
+
316
+ def _open(self) -> None:
317
+ self.tmp_path = self.out_dir / f"train_{len(self.shards):03d}.bin.tmp"
318
+ self.f = open(self.tmp_path, "wb")
319
+
320
+ def add(self, ids: np.ndarray, src_per_token: np.ndarray) -> bool:
321
+ """Append tokens; returns True once all blocks are written."""
322
+ pos = 0
323
+ while pos < len(ids):
324
+ blocks, target = self._target()
325
+ take = min(target - self.cur, len(ids) - pos)
326
+ self.f.write(ids[pos:pos + take].tobytes())
327
+ self.cur_counts += np.bincount(src_per_token[pos:pos + take], minlength=len(STREAMS))
328
+ self.cur += take
329
+ pos += take
330
+ if self.cur == target:
331
+ self._close_shard(blocks, int(ids[pos - 1]))
332
+ if self.blocks_done == self.total_blocks:
333
+ return True
334
+ return False
335
+
336
+ def _close_shard(self, blocks: int, last_token: int) -> None:
337
+ self.f.flush()
338
+ os.fsync(self.f.fileno())
339
+ self.f.close()
340
+ name = self.tmp_path.name.removesuffix(".tmp")
341
+ os.replace(self.tmp_path, self.out_dir / name)
342
+ self.shards.append({"file": name, "tokens": self.cur, "blocks": blocks,
343
+ "tokens_by_stream": dict(zip(STREAMS, self.cur_counts.tolist()))})
344
+ self.blocks_done += blocks
345
+ log(f"shard {name}: {blocks:,} blocks, {self.cur:,} tokens")
346
+ if self.blocks_done < self.total_blocks:
347
+ self._open()
348
+ self.f.write(np.array([last_token], dtype=np.uint16).tobytes()) # overlap token, counted in prior shard
349
+ self.cur = 1
350
+ self.cur_counts = np.zeros(len(STREAMS), dtype=np.int64)
351
+
352
+
353
+ def doc_lengths(path: Path, n_tokens: int) -> np.ndarray:
354
+ """Every document starts with <|endoftext|> and id 0 occurs nowhere else, so its positions delimit documents."""
355
+ starts = []
356
+ with open(path, "rb") as f:
357
+ for off in range(0, n_tokens, READ_CHUNK):
358
+ chunk = np.frombuffer(f.read(min(READ_CHUNK, n_tokens - off) * 2), dtype=np.uint16)
359
+ starts.append(np.flatnonzero(chunk == EOT_ID) + off)
360
+ starts = np.concatenate(starts)
361
+ assert starts[0] == 0, f"{path.name} does not start with <|endoftext|>"
362
+ return np.diff(np.append(starts, n_tokens))
363
+
364
+
365
+ class SequentialReader:
366
+ def __init__(self, path: Path):
367
+ self.f = open(path, "rb")
368
+ self.buf = np.empty(0, dtype=np.uint16)
369
+ self.pos = 0
370
+
371
+ def take(self, n: int) -> np.ndarray:
372
+ while len(self.buf) - self.pos < n:
373
+ more = np.frombuffer(self.f.read(READ_CHUNK * 2), dtype=np.uint16)
374
+ if more.size == 0:
375
+ raise EOFError(self.f.name)
376
+ self.buf = np.concatenate([self.buf[self.pos:], more])
377
+ self.pos = 0
378
+ out = self.buf[self.pos:self.pos + n]
379
+ self.pos += n
380
+ return out
381
+
382
+
383
+ def assemble(metas: dict, out_dir: Path, total_blocks: int, shard_tokens: int) -> dict:
384
+ """Interleave the documents of the four stream files in a seeded random order (per-document sampling at
385
+ proportions fixed for the whole run) and pack them into shards. Fast and local, so it always starts over."""
386
+ for p in out_dir.glob("train_*.bin*"):
387
+ p.unlink()
388
+ stream_dir = out_dir / "streams"
389
+ lengths = {}
390
+ for name in STREAMS:
391
+ lengths[name] = doc_lengths(stream_dir / f"{name}.bin", metas[name]["tokens"])
392
+ assert len(lengths[name]) == metas[name]["docs"], f"{name}: document count mismatch"
393
+ order = np.concatenate([np.full(len(lengths[n]), SRC_IDX[n], dtype=np.uint8) for n in STREAMS])
394
+ np.random.default_rng(SEED).shuffle(order)
395
+ readers = {n: SequentialReader(stream_dir / f"{n}.bin") for n in STREAMS}
396
+ used = dict.fromkeys(STREAMS, 0)
397
+ writer = ShardWriter(out_dir, total_blocks, shard_tokens)
398
+ t0, done = time.time(), False
399
+ chunks, srcs, doc_lens, pending = [], [], [], 0
400
+ for s in order.tolist():
401
+ name = STREAMS[s]
402
+ n = int(lengths[name][used[name]])
403
+ used[name] += 1
404
+ chunks.append(readers[name].take(n))
405
+ srcs.append(s)
406
+ doc_lens.append(n)
407
+ pending += n
408
+ if pending >= 4_000_000:
409
+ done = writer.add(np.concatenate(chunks), np.repeat(np.array(srcs, dtype=np.uint8), doc_lens))
410
+ chunks, srcs, doc_lens, pending = [], [], [], 0
411
+ if done:
412
+ break
413
+ if not done and chunks:
414
+ done = writer.add(np.concatenate(chunks), np.repeat(np.array(srcs, dtype=np.uint8), doc_lens))
415
+ if not done:
416
+ raise RuntimeError("stream files are too short for the requested number of blocks")
417
+ log(f"assembled {writer.blocks_done:,} blocks in {time.time() - t0:.0f}s; documents used {used}")
418
+
419
+ by_stream = {n: sum(s["tokens_by_stream"][n] for s in writer.shards) for n in STREAMS}
420
+ total = sum(by_stream.values())
421
+ by_domain = {d: sum(v for n, v in by_stream.items() if STREAM_DOMAIN[n] == d) for d in DOMAINS}
422
+ index_path = out_dir / "index.json"
423
+ index = json.loads(index_path.read_text()) if index_path.exists() else {}
424
+ for stale in ("probabilities", "token_caps", "skipped_docs_after_cap"):
425
+ index.pop(stale, None)
426
+ index.update({
427
+ "tokenizer": str(TOKENIZER_PATH.relative_to(ROOT)), "dtype": "uint16", "seq_len": SEQ, "block": SEQ + 1,
428
+ "stride": SEQ, "eot_id": EOT_ID, "seed": SEED,
429
+ "mix": {"method": "each sub-stream tokenized to its token budget, documents interleaved in a seeded random "
430
+ "order (per-document sampling at fixed proportions)",
431
+ "target_share_by_stream": STREAM_SHARE, "streams": metas, "documents_used": used},
432
+ "blocks": writer.blocks_done, "train_steps": STEPS, "seqs_per_step": SEQS_PER_STEP,
433
+ "margin_steps": MARGIN_STEPS if total_blocks == FULL_BLOCKS else 0,
434
+ "shards": writer.shards,
435
+ "total": {
436
+ "tokens": total, "tokens_by_stream": by_stream, "tokens_by_domain": by_domain,
437
+ "share_by_stream": {n: by_stream[n] / total for n in STREAMS},
438
+ "share_by_domain": {d: by_domain[d] / total for d in DOMAINS},
439
+ "python_share_of_code": by_stream["code_py"] / by_domain["code"],
440
+ },
441
+ "throughput": {
442
+ "tok_s_end_to_end_by_stream": {n: metas[n]["tok_s_end_to_end"] for n in STREAMS},
443
+ "tok_s_tokenizer_capacity_by_stream": {n: metas[n]["tok_s_tokenizer_capacity"] for n in STREAMS},
444
+ "num_proc": NUM_PROC,
445
+ },
446
+ })
447
+ write_json(index_path, index)
448
+ return index
449
+
450
+
451
+ # ---------------------------------------------------------------- 4. validation
452
+ def validate(out_dir: Path) -> None:
453
+ index = json.loads((out_dir / "index.json").read_text())
454
+ tok = Tokenizer.from_file(str(TOKENIZER_PATH))
455
+ vocab = tok.get_vocab_size()
456
+ rng = np.random.default_rng(0)
457
+ prev_last = None
458
+ for s in index["shards"]:
459
+ arr = np.fromfile(out_dir / s["file"], dtype=np.uint16) # sequential read; mmap over DrvFs is slow
460
+ assert len(arr) == s["tokens"] == s["blocks"] * SEQ + 1, f"{s['file']}: size mismatch"
461
+ assert int(arr.max()) < vocab, f"{s['file']}: token id out of range"
462
+ if prev_last is not None:
463
+ assert int(arr[0]) == prev_last, f"{s['file']}: overlap token mismatch"
464
+ prev_last = int(arr[-1])
465
+ eot = int((arr == EOT_ID).sum())
466
+ j = int(rng.integers(s["blocks"]))
467
+ text = tok.decode(arr[j * SEQ:j * SEQ + SEQ + 1].tolist(), skip_special_tokens=False)
468
+ log(f"{s['file']} ok: {s['blocks']:,} blocks, {eot:,} docs (mean {len(arr) / max(eot, 1):,.0f} tokens/doc) | "
469
+ f"block {j}: {text[:160]!r}")
470
+ del arr
471
+ for d, v in index.get("val", {}).items():
472
+ arr = np.fromfile(VAL_DIR / v["file"], dtype=np.uint16)
473
+ assert len(arr) == v["tokens"] and int(arr.max()) < vocab
474
+ log(f"val_{d} ok: {len(arr):,} tokens, {v['bytes']:,} bytes, by stream {v['tokens_by_stream']}")
475
+ t = index["total"]
476
+ log(f"blocks {index['blocks']:,} (training needs {STEPS * SEQS_PER_STEP:,}) | shares by domain: "
477
+ + ", ".join(f"{d} {100 * x:.2f}%" for d, x in t["share_by_domain"].items())
478
+ + f" | python in code {100 * t['python_share_of_code']:.1f}%")
479
+
480
+
481
+ def main() -> None:
482
+ ap = argparse.ArgumentParser()
483
+ ap.add_argument("--out", type=Path, default=VAL_DIR)
484
+ ap.add_argument("--blocks", type=int, default=FULL_BLOCKS)
485
+ ap.add_argument("--shard-tokens", type=int, default=500_000_000)
486
+ ap.add_argument("--validate", action="store_true", help="only validate an existing output directory")
487
+ ap.add_argument("--max-rss-gb", type=float, default=8.0,
488
+ help="memory guard: checkpoint and restart when this process plus its workers exceed it")
489
+ ap.add_argument("--keep-streams", action="store_true", help="keep data/tokens/streams after validation")
490
+ args = ap.parse_args()
491
+ out_dir = args.out if args.out.is_absolute() else ROOT / args.out
492
+
493
+ if args.validate:
494
+ validate(out_dir)
495
+ return
496
+
497
+ out_dir.mkdir(parents=True, exist_ok=True)
498
+ start_memory_watchdog()
499
+ tok = load_tokenizer()
500
+ splits = file_splits(SPLITS_PATH)
501
+ build_holdout(splits, tok)
502
+
503
+ target_tokens = args.blocks * SEQ + 1
504
+ stream_dir = out_dir / "streams"
505
+ metas = {}
506
+ for name in STREAMS:
507
+ meta_path = stream_dir / f"{name}.json"
508
+ if meta_path.exists():
509
+ metas[name] = json.loads(meta_path.read_text())
510
+ continue
511
+ budget = int(STREAM_SHARE[name] * target_tokens * STREAM_SLACK) + 1
512
+ tokenize_stream(name, splits[STREAM_DOMAIN[name]]["train"], budget, args.max_rss_gb, stream_dir)
513
+ sys.stdout.flush()
514
+ os._exit(RESTART_EXIT_CODE) # next stream in a fresh process, with a fresh heap
515
+
516
+ index = assemble(metas, out_dir, args.blocks, args.shard_tokens)
517
+ log(json.dumps({k: index[k] for k in ("total", "throughput")}, indent=2))
518
+ validate(out_dir)
519
+ if not args.keep_streams:
520
+ for p in stream_dir.glob("*"):
521
+ p.unlink()
522
+ stream_dir.rmdir()
523
+ log("stream files deleted")
524
+ sys.stdout.flush()
525
+ os._exit(0) # streaming threads can stall a normal interpreter exit
526
+
527
+
528
+ if __name__ == "__main__":
529
+ main()
scripts/publish.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Export, document and publish GPT-U-20M to the Hugging Face Hub.
2
+
3
+ python scripts/publish.py export # checkpoints -> out/hf (step 19,840) and out/hf-stable-15872 (weights only)
4
+ python scripts/publish.py card # out/hf/README.md from eval results, data index and training logs
5
+ python scripts/publish.py upload # needs $HF_TOKEN: main branch + stable-15872 branch
6
+ python scripts/publish.py verify # fresh download into an empty cache, load with AutoModelForCausalLM, generate
7
+ """
8
+ import argparse
9
+ import json
10
+ import os
11
+ import shutil
12
+ import sys
13
+ import tempfile
14
+ from datetime import datetime
15
+ from pathlib import Path
16
+
17
+ import torch
18
+ from huggingface_hub import HfApi
19
+ from tokenizers import Tokenizer, processors
20
+ from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig, PreTrainedTokenizerFast
21
+
22
+ from common import CKPT_DIR, DATA_DIR, LOG_DIR, OUT_DIR, ROOT, TOKENIZER_DIR, build_model
23
+
24
+ REPO_ID = "DedeProGames/GPT-U-20M"
25
+ FINAL_STEP, STABLE_STEP = 19_840, 15_872
26
+ STABLE_BRANCH = f"stable-{STABLE_STEP}"
27
+ HF_DIR = OUT_DIR / "hf"
28
+ STABLE_DIR = OUT_DIR / f"hf-{STABLE_BRANCH}"
29
+ STAGE_DIR = OUT_DIR / "publish_main"
30
+ EOT = "<|endoftext|>"
31
+ CHANCE = {"arc_easy": 25.0, "piqa": 50.0, "hellaswag": 25.0, "lambada_openai": 0.0, "winogrande": 50.0}
32
+
33
+
34
+ # ---------------------------------------------------------------- export
35
+ def export_model(step: int, out_dir: Path) -> None:
36
+ ckpt = torch.load(CKPT_DIR / f"step_{step:05d}.pt", map_location="cpu", weights_only=False)
37
+ model = build_model(init=False)
38
+ model.load_state_dict(ckpt["model"])
39
+ out_dir.mkdir(parents=True, exist_ok=True)
40
+ model.to(torch.bfloat16).save_pretrained(out_dir)
41
+ GenerationConfig(bos_token_id=0, eos_token_id=0, pad_token_id=0, do_sample=True, temperature=0.8, top_p=0.95,
42
+ max_new_tokens=256).save_pretrained(out_dir)
43
+
44
+
45
+ def export_tokenizer(out_dir: Path) -> None:
46
+ """Same vocabulary/merges as training; the published copy prepends <|endoftext|> (the training BOS) on encode."""
47
+ tok = Tokenizer.from_file(str(TOKENIZER_DIR / "tokenizer.json"))
48
+ tok.post_processor = processors.TemplateProcessing(single=f"{EOT} $A", pair=f"{EOT} $A {EOT} $B",
49
+ special_tokens=[(EOT, 0)])
50
+ PreTrainedTokenizerFast(tokenizer_object=tok, bos_token=EOT, eos_token=EOT, pad_token=EOT, model_max_length=1024,
51
+ clean_up_tokenization_spaces=False).save_pretrained(out_dir)
52
+
53
+
54
+ def cmd_export(_args) -> None:
55
+ export_model(FINAL_STEP, HF_DIR)
56
+ export_tokenizer(HF_DIR)
57
+ export_model(STABLE_STEP, STABLE_DIR)
58
+ for d in (HF_DIR, STABLE_DIR):
59
+ print(d, sorted(p.name for p in d.iterdir()))
60
+
61
+
62
+ # ---------------------------------------------------------------- model card
63
+ def read_jsonl(path: Path) -> list[dict]:
64
+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
65
+
66
+
67
+ def lm_eval_rows() -> list[str]:
68
+ files = sorted((OUT_DIR / "lm_eval").rglob("results_*.json"))
69
+ if not files:
70
+ return ["Benchmarks were not run."]
71
+ results = json.loads(files[-1].read_text())["results"]
72
+ rows = ["| Task | Metric | GPT-U-20M | Chance |", "|---|---|---:|---:|"]
73
+ for task, chance in CHANCE.items():
74
+ r = results.get(task, {})
75
+ for metric in ("acc,none", "acc_norm,none", "perplexity,none"):
76
+ if metric in r:
77
+ name = metric.split(",")[0]
78
+ value = f"{r[metric]:.2f}" if name == "perplexity" else f"{100 * r[metric]:.2f}"
79
+ rows.append(f"| {task} | {name} | {value} | {'—' if name == 'perplexity' else f'{chance:.0f}'} |")
80
+ return rows
81
+
82
+
83
+ def training_stats() -> dict:
84
+ rows = read_jsonl(LOG_DIR / "train.jsonl")
85
+ steps = [r for r in rows if "event" not in r]
86
+ events = [r for r in rows if "event" in r]
87
+ # Active time only: the run was paused for days while the machine was off, then resumed from checkpoints.
88
+ times = sorted(datetime.fromisoformat(r["wall_clock"]) for r in steps)
89
+ active = sum((b - a).total_seconds() for a, b in zip(times, times[1:]) if (b - a).total_seconds() < 300)
90
+ return {
91
+ "hours": active / 3600,
92
+ "tok_s": sum(r["tok_s"] for r in steps) / len(steps),
93
+ "mfu": sum(r["mfu"] for r in steps) / len(steps),
94
+ "resumes": sum(r["event"] == "resume" for r in events),
95
+ "loss_guard": sum(r["event"] == "loss_guard" for r in events),
96
+ "compile": next((r["mode"] for r in reversed(events) if r["event"] == "compile"), "?"),
97
+ "max_temp": max(max(t for t in (r.get("gpu0_temp"), r.get("gpu1_temp")) if t is not None) for r in steps),
98
+ }
99
+
100
+
101
+ def build_card() -> str:
102
+ data = json.loads((DATA_DIR / "index.json").read_text())
103
+ ev = json.loads((OUT_DIR / "eval.json").read_text())
104
+ tokrep = json.loads((LOG_DIR / "tokenizer_report.json").read_text())
105
+ ts = training_stats()
106
+ seen = FINAL_STEP * 131_072
107
+ share = data["total"]["share_by_domain"]
108
+ fert = tokrep["fertility"]
109
+ val = data["val"]
110
+ names = {"dclm": "DCLM-baseline", "edu": "FineWeb-Edu", "code": "The Stack v3 (code)"}
111
+
112
+ lines = f"""---
113
+ license: apache-2.0
114
+ datasets:
115
+ - mlfoundations/dclm-baseline-1.0
116
+ - HuggingFaceFW/fineweb-edu
117
+ - HuggingFaceCode/stack-v3-train
118
+ language: en
119
+ library_name: transformers
120
+ pipeline_tag: text-generation
121
+ tags:
122
+ - gpt-u
123
+ - tiny-lm
124
+ - pretrained-from-scratch
125
+ ---
126
+
127
+ # GPT-U-20M
128
+
129
+ A 20.5M-parameter Llama-architecture language model pretrained from scratch on 2.6B tokens of web text, educational text and code.
130
+
131
+ ## Architecture
132
+
133
+ | | |
134
+ |---|---|
135
+ | Type | decoder-only transformer, `LlamaForCausalLM`: RoPE, SwiGLU, RMSNorm, pre-norm, no biases |
136
+ | Parameters | 20,453,760 (6,291,456 tied embedding + 8 × 1,770,240 per block + 384 final norm) |
137
+ | Layers | 8 |
138
+ | Hidden size | 384 |
139
+ | Attention | 6 heads × 64 dims, full multi-head (no GQA), SDPA |
140
+ | MLP | SwiGLU, intermediate size 1,024 |
141
+ | Vocabulary | 16,384 (byte-level BPE, trained on the same mix) |
142
+ | Context length | 1,024 tokens |
143
+ | RoPE θ | 10,000 |
144
+ | Input/output embeddings | tied |
145
+
146
+ The 16,384-token vocabulary keeps the embedding at 31% of the parameters (a 50k vocabulary would need 19.3M parameters at width 384) and lets tokens be stored as `uint16`.
147
+
148
+ **Tokenizer.** Byte-level BPE with a cl100k-style split that keeps whitespace runs whole (Python indentation), one token per digit, and `<|endoftext|>` (id 0) as BOS/EOS/padding. Round-trip `decode(encode(x)) == x` holds on 1,000 held-out samples (tabs, CRLF, emoji, CJK, RTL, control characters).
149
+
150
+ | Held-out domain | Tokens / word | Bytes / token |
151
+ |---|---:|---:|
152
+ | DCLM | {fert['dclm']['tokens_per_word']:.2f} | {fert['dclm']['bytes_per_token']:.2f} |
153
+ | FineWeb-Edu | {fert['edu']['tokens_per_word']:.2f} | {fert['edu']['bytes_per_token']:.2f} |
154
+ | Code (27% Python) | {fert['code']['tokens_per_word']:.2f} | {fert['code']['bytes_per_token']:.2f} |
155
+ | Python only | {fert['code_python_only']['tokens_per_word']:.2f} | {fert['code_python_only']['bytes_per_token']:.2f} |
156
+
157
+ ## Training data
158
+
159
+ One epoch over 2.6B tokens, no repetition:
160
+
161
+ | Dataset | Target share | Realized share | Tokens seen (≈) |
162
+ |---|---:|---:|---:|
163
+ | [mlfoundations/dclm-baseline-1.0](https://huggingface.co/datasets/mlfoundations/dclm-baseline-1.0) | 45% | {100 * share['dclm']:.2f}% | {share['dclm'] * seen / 1e9:.2f}B |
164
+ | [HuggingFaceFW/fineweb-edu](https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu) (`sample-10BT`) | 35% | {100 * share['edu']:.2f}% | {share['edu'] * seen / 1e9:.2f}B |
165
+ | [HuggingFaceCode/stack-v3-train](https://huggingface.co/datasets/HuggingFaceCode/stack-v3-train) | 20% | {100 * share['code']:.2f}% | {share['code'] * seen / 1e9:.2f}B |
166
+
167
+ - Each source is streamed from the Hub and tokenized up to its token budget; the documents are then interleaved **per document** in a seeded random order, i.e. with fixed proportions for the whole run (no domain curriculum), so the realized shares match the targets exactly. (Holding the four streams open at once was avoided: it needed 7–8 GB of RAM and destabilized the training machine.)
168
+ - The Stack v3 is grouped by repository; repositories were split into individual files, vendored files dropped, and Python held at {100 * data['total']['python_share_of_code']:.1f}% of the code tokens (it is ~4% of Stack v3 naturally).
169
+ - Documents are separated by `<|endoftext|>` and packed into contiguous 1,025-token blocks (1,024 inputs + 1 shifted target), no padding. Batches are sampled from a seeded permutation of all blocks.
170
+ - Validation holdouts (2M tokens per domain) come from source files that never fed training or the tokenizer.
171
+
172
+ ## Training
173
+
174
+ | Hyperparameter | Value |
175
+ |---|---|
176
+ | Tokens per step | 131,072 (2 GPUs × 32 sequences × 1,024 tokens × 2 accumulation steps) |
177
+ | Steps | 19,840 |
178
+ | Optimizer | AdamW, β = (0.9, 0.95), ε = 1e-8 |
179
+ | Peak learning rate | 1.8e-3 |
180
+ | Schedule | WSD: 500 warmup steps → constant to step 15,872 → linear decay to 1.8e-4 at step 19,840 |
181
+ | Weight decay | 0.1 on 2D matrices only (none on norms and embeddings) |
182
+ | Gradient clipping | 1.0 |
183
+ | z-loss | 1e-4 |
184
+ | Dropout | 0 |
185
+ | Initialization | N(0, 0.02); `o_proj` and `down_proj` scaled by 1/√(2·8) |
186
+ | Precision | bf16 autocast, fp32 master weights |
187
+
188
+ Trained on 2× RTX 3060 12GB (no NVLink) under WSL2 with PyTorch DDP and `torch.compile` (mode: {ts['compile']}): {ts['hours']:.1f} h of active training time, {ts['tok_s']:,.0f} tokens/s on average (MFU ≈ {100 * ts['mfu']:.0f}% of the GPUs' measured bf16 matmul throughput), max GPU temperature {ts['max_temp']}°C, {ts['resumes']} automatic resume(s) from checkpoints after the machine was shut down, {ts['loss_guard']} loss-spike rollback(s).
189
+
190
+ ## Results
191
+
192
+ Validation loss on the 2M-token holdouts (1,600 fixed 1,024-token windows per domain) and bits per byte, `bpb = loss_nats × tokens / (bytes × ln 2)`, which is comparable across tokenizers:
193
+
194
+ | Domain | Val loss (nats/token) | Bits per byte |
195
+ |---|---:|---:|
196
+ """.splitlines()
197
+ for d in ("dclm", "edu", "code"):
198
+ lines.append(f"| {names[d]} | {ev[d]['loss']:.4f} | {ev[d]['bpb']:.4f} |")
199
+ lines.append(f"| **Aggregate** | **{ev['aggregate']['loss']:.4f}** | **{ev['aggregate']['bpb']:.4f}** |")
200
+ lines += ["", "The aggregate is the equal-weight mean of the three holdouts (same number of tokens each). Code tokens "
201
+ "are far easier to predict than prose with this tokenizer, which pulls the aggregate down; the prose domains "
202
+ f"({ev['edu']['loss']:.2f}–{ev['dclm']['loss']:.2f} nats/token) are the fairer comparison point for "
203
+ "web-text models, and bits per byte is the fairer one across tokenizers."]
204
+ lines += ["", "Zero-shot benchmarks ([lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness)). "
205
+ "`<|endoftext|>` is prepended as BOS. hellaswag and winogrande sit at chance, as expected at 20M parameters; "
206
+ "arc_easy and piqa land clearly above it, which reflects surface lexical knowledge more than reasoning. "
207
+ "They are reported for transparency, not as a quality signal.",
208
+ ""]
209
+ lines += lm_eval_rows()
210
+ lines += f"""
211
+ Sample generations (temperature 0.8, top-p 0.95) are in [`out/samples.md`](out/samples.md).
212
+
213
+ ## Loss curve
214
+
215
+ ![Training and validation loss](out/loss.png)
216
+
217
+ ## Usage
218
+
219
+ ```python
220
+ import torch
221
+ from transformers import AutoModelForCausalLM, AutoTokenizer
222
+
223
+ tokenizer = AutoTokenizer.from_pretrained("{REPO_ID}")
224
+ model = AutoModelForCausalLM.from_pretrained("{REPO_ID}")
225
+
226
+ inputs = tokenizer("The history of the Roman Empire", return_tensors="pt") # prepends <|endoftext|> as BOS
227
+ output = model.generate(**inputs, max_new_tokens=100, do_sample=True, temperature=0.8, top_p=0.95)
228
+ print(tokenizer.decode(output[0], skip_special_tokens=True))
229
+ ```
230
+
231
+ ## Checkpoints
232
+
233
+ - `main`: final weights (step 19,840, end of the decay phase).
234
+ - [`{STABLE_BRANCH}`](https://huggingface.co/{REPO_ID}/tree/{STABLE_BRANCH}): weights at step 15,872, the end of the constant-learning-rate phase, meant for continued pretraining (e.g. extending to 4–5B tokens before decaying again). Load with `revision="{STABLE_BRANCH}"`.
235
+
236
+ ## Limitations
237
+
238
+ - **It is tiny.** 20M parameters is a research and teaching scale; the model has shallow world knowledge and weak reasoning.
239
+ - **Heavily over-trained for its size by design:** 127 tokens per parameter, about 6× the Chinchilla-optimal ratio (~20).
240
+ - **Not for production use.** It hallucinates freely and produces fluent but often false statements.
241
+ - **Generated code is not functional.** It imitates the surface form of code; do not run it.
242
+ - English only (web and educational text); no instruction tuning, no safety tuning. Web data can carry biases and offensive content.
243
+ - Context is limited to 1,024 tokens.
244
+
245
+ ## Data provenance and licenses
246
+
247
+ | Source | License | Notes |
248
+ |---|---|---|
249
+ | DCLM-baseline 1.0 | CC-BY-4.0 | Common Crawl web text filtered by DataComp-LM; see the dataset card. |
250
+ | FineWeb-Edu (`sample-10BT`) | ODC-By 1.0 | Common Crawl pages filtered for educational value; use is also subject to Common Crawl's terms of use. |
251
+ | The Stack v3 (train) | ODC-By | GitHub code as of August 2025; files are permissively licensed or carry no detected license (non-permissive files excluded upstream), PII-redacted, with an opt-out process. Individual files keep their original licenses. |
252
+
253
+ The model weights are released under **Apache-2.0**. Tokenized data is not redistributed.
254
+
255
+ ## Reproducibility
256
+
257
+ Everything used to build this model is in the repository: `scripts/` (tokenizer training, data preparation, training, evaluation, publishing), `configs/model.json`, `logs/train.jsonl` (every 10 steps: loss, lr, grad norm, throughput, MFU, GPU temperatures, memory), `logs/tokenizer_report.json` and `out/data_index.json` (token counts per shard and domain, holdout bytes). Raw evaluation outputs: `out/eval.json` and `out/lm_eval_results.json`.
258
+ """.splitlines()
259
+ return "\n".join(lines) + "\n"
260
+
261
+
262
+ def cmd_card(_args) -> None:
263
+ card = build_card()
264
+ (HF_DIR / "README.md").write_text(card, encoding="utf-8")
265
+ print(card)
266
+
267
+
268
+ # ---------------------------------------------------------------- upload
269
+ def stage_main() -> Path:
270
+ if STAGE_DIR.exists():
271
+ shutil.rmtree(STAGE_DIR)
272
+ shutil.copytree(HF_DIR, STAGE_DIR)
273
+ shutil.copytree(ROOT / "scripts", STAGE_DIR / "scripts", ignore=shutil.ignore_patterns("__pycache__"))
274
+ (STAGE_DIR / "configs").mkdir()
275
+ shutil.copy2(ROOT / "configs" / "model.json", STAGE_DIR / "configs" / "model.json")
276
+ (STAGE_DIR / "logs").mkdir()
277
+ for name in ("train.jsonl", "tokenizer_report.json"):
278
+ shutil.copy2(LOG_DIR / name, STAGE_DIR / "logs" / name)
279
+ (STAGE_DIR / "out").mkdir()
280
+ for name in ("loss.png", "samples.md", "eval.json"):
281
+ shutil.copy2(OUT_DIR / name, STAGE_DIR / "out" / name)
282
+ shutil.copy2(DATA_DIR / "index.json", STAGE_DIR / "out" / "data_index.json")
283
+ results = sorted((OUT_DIR / "lm_eval").rglob("results_*.json"))
284
+ if results:
285
+ shutil.copy2(results[-1], STAGE_DIR / "out" / "lm_eval_results.json")
286
+ return STAGE_DIR
287
+
288
+
289
+ def cmd_upload(_args) -> None:
290
+ token = os.environ.get("HF_TOKEN")
291
+ if not token:
292
+ sys.exit("HF_TOKEN is not set: nothing uploaded (out/hf and out/hf-stable-15872 are ready).")
293
+ api = HfApi(token=token)
294
+ api.create_repo(REPO_ID, repo_type="model", private=False, exist_ok=True)
295
+ if STABLE_BRANCH not in {b.name for b in api.list_repo_refs(REPO_ID).branches}:
296
+ first_commit = api.list_repo_commits(REPO_ID)[-1].commit_id # branch from the empty initial commit
297
+ api.create_branch(REPO_ID, branch=STABLE_BRANCH, revision=first_commit)
298
+ api.upload_folder(repo_id=REPO_ID, folder_path=STABLE_DIR, revision=STABLE_BRANCH,
299
+ commit_message=f"Weights at step {STABLE_STEP:,} (end of the stable WSD phase)")
300
+ api.upload_folder(repo_id=REPO_ID, folder_path=stage_main(),
301
+ commit_message="GPT-U-20M: final weights, tokenizer, model card, scripts and logs")
302
+ print(f"uploaded: https://huggingface.co/{REPO_ID}")
303
+
304
+
305
+ # ---------------------------------------------------------------- verification
306
+ def cmd_verify(_args) -> None:
307
+ with tempfile.TemporaryDirectory() as cache:
308
+ tokenizer = AutoTokenizer.from_pretrained(REPO_ID, cache_dir=cache)
309
+ model = AutoModelForCausalLM.from_pretrained(REPO_ID, cache_dir=cache)
310
+ n_params = sum(p.numel() for p in model.parameters())
311
+ inputs = tokenizer("The history of the Roman Empire", return_tensors="pt")
312
+ assert inputs.input_ids[0, 0].item() == 0, "tokenizer should prepend <|endoftext|>"
313
+ torch.manual_seed(0)
314
+ out = model.generate(**inputs, max_new_tokens=60, do_sample=True, temperature=0.8, top_p=0.95)
315
+ print(f"main: {n_params:,} params | {tokenizer.decode(out[0], skip_special_tokens=True)!r}")
316
+ stable = AutoModelForCausalLM.from_pretrained(REPO_ID, revision=STABLE_BRANCH, cache_dir=cache)
317
+ print(f"{STABLE_BRANCH}: {sum(p.numel() for p in stable.parameters()):,} params loaded")
318
+
319
+
320
+ def main() -> None:
321
+ ap = argparse.ArgumentParser()
322
+ ap.add_argument("command", choices=["export", "card", "upload", "verify"])
323
+ args = ap.parse_args()
324
+ {"export": cmd_export, "card": cmd_card, "upload": cmd_upload, "verify": cmd_verify}[args.command](args)
325
+
326
+
327
+ if __name__ == "__main__":
328
+ main()
scripts/run_prepare.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Run prepare_data.py to completion. Exit code 75 means "start a fresh process": the next stage (each Hub stream is
3
+ # tokenized in its own process) or a resume after the memory guard checkpointed.
4
+ # bash scripts/run_prepare.sh [prepare_data.py args]
5
+ set -uo pipefail
6
+ cd "$(dirname "$0")"
7
+ VENV=${VENV:-$HOME/venvs/gpt-u}
8
+ LOG=${LOG:-../logs/prepare_full.log}
9
+ for attempt in $(seq 1 100); do
10
+ env HF_HUB_DISABLE_PROGRESS_BARS=1 MALLOC_ARENA_MAX=2 "$VENV/bin/python" -u prepare_data.py "$@" 2>&1 \
11
+ | grep --line-buffered -v 'unauthenticated requests' | tee -a "$LOG"
12
+ rc=${PIPESTATUS[0]}
13
+ if [ "$rc" -ne 75 ]; then
14
+ echo "[run_prepare] finished with exit code $rc after $attempt run(s)" | tee -a "$LOG"
15
+ exit "$rc"
16
+ fi
17
+ echo "[run_prepare] fresh process #$((attempt + 1)) at $(date -Is)" | tee -a "$LOG"
18
+ done
scripts/run_train.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Start GPT-U-20M training in a detached tmux session with a persistent log. Re-running resumes automatically.
3
+ # scripts/run_train.sh -> session "gptu", full run, log logs/gptu.out
4
+ # SESSION=smoke scripts/run_train.sh --smoke
5
+ set -euo pipefail
6
+ cd "$(dirname "$0")/.."
7
+ SESSION=${SESSION:-gptu}
8
+ VENV=${VENV:-$HOME/venvs/gpt-u}
9
+ CACHE=${CACHE:-/mnt/c/Users/andre/gpt-u-20m-data/cache} # compiler caches off the exFAT-hosted WSL disk
10
+ ENVS="NCCL_P2P_DISABLE=1 NCCL_IB_DISABLE=1 CUDA_DEVICE_ORDER=PCI_BUS_ID PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True OMP_NUM_THREADS=2 TORCHINDUCTOR_CACHE_DIR=$CACHE/inductor TRITON_CACHE_DIR=$CACHE/triton"
11
+ # The env goes inside the command: a running tmux server would not inherit this shell's exports.
12
+ tmux new-session -d -s "$SESSION" \
13
+ "cd $PWD && env $ENVS $VENV/bin/torchrun --standalone --nproc_per_node=2 scripts/train.py $* 2>&1 | tee -a logs/$SESSION.out"
14
+ echo "tmux session '$SESSION' started, log: logs/$SESSION.out"
scripts/sources.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Streaming document sources for the GPT-U-20M data mix.
2
+
3
+ Four sub-streams feed the mix: `dclm`, `edu`, and the Stack v3 slice split by file language into `code_py` and
4
+ `code_other`, so Python can be held at ~27% of the code tokens (it is only ~4% of Stack v3 naturally).
5
+ Each source's file list is split once: its last file is the holdout file and never feeds the tokenizer corpus
6
+ or the training shards.
7
+ """
8
+ import json
9
+ import random
10
+ from pathlib import Path
11
+
12
+ import pyarrow as pa
13
+ import pyarrow.compute as pc
14
+ from datasets import Features, Value, load_dataset
15
+ from huggingface_hub import HfFileSystem
16
+
17
+ SEED = 20_453_760
18
+ MIX = {"dclm": 0.45, "edu": 0.35, "code": 0.20}
19
+ PYTHON_SHARE = 0.27 # spec: ~25-30% Python inside the code slice
20
+ STREAMS = ("dclm", "edu", "code_py", "code_other")
21
+ STREAM_DOMAIN = {"dclm": "dclm", "edu": "edu", "code_py": "code", "code_other": "code"}
22
+ STREAM_SHARE = {
23
+ "dclm": MIX["dclm"],
24
+ "edu": MIX["edu"],
25
+ "code_py": MIX["code"] * PYTHON_SHARE,
26
+ "code_other": MIX["code"] * (1 - PYTHON_SHARE),
27
+ }
28
+ SOURCES = { # domain -> (dataset repo, file glob inside the repo)
29
+ "dclm": ("mlfoundations/dclm-baseline-1.0", "global-shard_*/local-shard_*/*.jsonl.zst"),
30
+ "edu": ("HuggingFaceFW/fineweb-edu", "sample/10BT/*.parquet"), # uniform sample over all CC dumps
31
+ "code": ("HuggingFaceCode/stack-v3-train", "data/*.parquet"),
32
+ }
33
+ FEATURES = Features({"text": Value("string"), "src": Value("string")})
34
+
35
+
36
+ def file_splits(cache_path: Path) -> dict:
37
+ """{domain: {"train": [...], "holdout": [...]}}. Train order is a fixed shuffle, cached so every script agrees."""
38
+ if cache_path.exists():
39
+ return json.loads(cache_path.read_text())
40
+ fs = HfFileSystem()
41
+ splits = {}
42
+ for domain, (repo, pattern) in SOURCES.items():
43
+ prefix = f"datasets/{repo}/"
44
+ files = sorted(p[len(prefix):] for p in fs.glob(prefix + pattern))
45
+ train = files[:-1]
46
+ random.Random(SEED).shuffle(train)
47
+ splits[domain] = {"train": train, "holdout": files[-1:]}
48
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
49
+ cache_path.write_text(json.dumps(splits, indent=1))
50
+ return splits
51
+
52
+
53
+ def _code_files(table: pa.Table, python: bool, src: str) -> pa.Table:
54
+ """Repository rows -> one row per non-vendor, non-empty file of the requested language group."""
55
+ files = pc.list_flatten(table["files"])
56
+ content = pc.struct_field(files, "content")
57
+ is_py = pc.equal(pc.struct_field(files, "language"), "Python")
58
+ keep = pc.and_(pc.invert(pc.struct_field(files, "is_vendor")), is_py if python else pc.invert(is_py))
59
+ keep = pc.and_(keep, pc.greater(pc.binary_length(content), 0))
60
+ text = pc.filter(content, keep)
61
+ return pa.table({"text": text, "src": pa.array([src] * len(text), pa.string())})
62
+
63
+
64
+ def _tag(table: pa.Table, src: str) -> pa.Table:
65
+ return pa.table({"text": table["text"], "src": pa.array([src] * len(table), pa.string())})
66
+
67
+
68
+ def open_stream(name: str, files: list[str]):
69
+ """Streaming IterableDataset with columns `text` and `src` for one sub-stream, reading `files` in order."""
70
+ domain = STREAM_DOMAIN[name]
71
+ repo = SOURCES[domain][0]
72
+ if domain == "code":
73
+ ds = load_dataset(repo, data_files=files, split="train", streaming=True, columns=["files"])
74
+ ds = ds.with_format("arrow").map(_code_files, batched=True, batch_size=64, remove_columns=["files"],
75
+ features=FEATURES, fn_kwargs={"python": name == "code_py", "src": name})
76
+ else:
77
+ kwargs = {"columns": ["text"]} if domain == "edu" else {}
78
+ ds = load_dataset(repo, data_files=files, split="train", streaming=True, **kwargs).select_columns(["text"])
79
+ ds = ds.with_format("arrow").map(_tag, batched=True, batch_size=1000, features=FEATURES, fn_kwargs={"src": name})
80
+ return ds.with_format(None)
scripts/train.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GPT-U-20M pretraining on 2x RTX 3060 with DDP.
2
+
3
+ scripts/run_train.sh # full run in tmux (auto-resumes from the newest checkpoint)
4
+ SESSION=smoke scripts/run_train.sh --smoke # 200-step smoke test on ~30M pilot tokens
5
+
6
+ bf16 autocast over fp32 master weights, AdamW + WSD schedule, z-loss, grad clip, torch.compile with an eager fallback.
7
+ Batches are drawn from a seeded permutation of token blocks indexed by (step, rank, micro-step), so resuming only needs
8
+ the step. Rank 0 appends to the jsonl log every 10 steps, checkpoints atomically every 500 steps, evaluates every
9
+ 1,000, rewrites STATUS.json at each checkpoint and redraws the loss curve every 2,000.
10
+ """
11
+ import argparse
12
+ import json
13
+ import math
14
+ import os
15
+ import shutil
16
+ import signal
17
+ import subprocess
18
+ import threading
19
+ import time
20
+ from collections import deque
21
+ from contextlib import nullcontext
22
+ from datetime import datetime, timedelta
23
+ from pathlib import Path
24
+
25
+ os.environ.setdefault("NCCL_P2P_DISABLE", "1") # no NVLink: P2P under WSL2 hangs the first all-reduce silently
26
+ os.environ.setdefault("NCCL_IB_DISABLE", "1")
27
+ os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID") # CUDA ids == nvidia-smi ids (temperature logging)
28
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
29
+
30
+ import numpy as np
31
+ import torch
32
+ import torch.distributed as dist
33
+ from torch.nn.parallel import DistributedDataParallel as DDP
34
+
35
+ from common import CKPT_DIR, DATA_DIR, EXPECTED_PARAMS, LOG_DIR, OUT_DIR, ROOT, build_model
36
+ from evaluate import val_losses
37
+ from plot import plot_loss
38
+
39
+ # ---------------------------------------------------------------- spec (closed)
40
+ SEQ = 1024
41
+ MICRO_BATCH = 32
42
+ TOKENS_PER_STEP = 131_072
43
+ SEQS_PER_STEP = TOKENS_PER_STEP // SEQ
44
+ TOTAL_STEPS = 19_840
45
+ WARMUP_STEPS = 500
46
+ STABLE_END = 15_872
47
+ PEAK_LR, MIN_LR = 1.8e-3, 1.8e-4
48
+ BETAS, EPS = (0.9, 0.95), 1e-8
49
+ WEIGHT_DECAY = 0.1
50
+ GRAD_CLIP = 1.0
51
+ Z_LOSS = 1e-4
52
+ DATA_SEED = 20_453_760
53
+
54
+ # ---------------------------------------------------------------- run safety
55
+ LOG_EVERY = 10
56
+ KEEP_LAST = 2
57
+ INIT_LOSS_RANGE = (9.2, 10.2) # ln(16384) = 9.70
58
+ SPIKE_WINDOW, SPIKE_DELTA, SPIKE_SKIP_STEPS, MAX_SPIKES = 100, 1.0, 200, 3
59
+ MIN_TOK_S, SLOW_STEPS = 45_000, 200
60
+ HOT_C, HOT_STEPS = 83, 100
61
+ COMPILE_TIMEOUT_S = 600
62
+
63
+ RUNS = {
64
+ "train": dict(data_dir=DATA_DIR, max_blocks=None, steps=TOTAL_STEPS, ckpt_every=500, eval_every=1000,
65
+ plot_every=2000, milestones={500, 5_000, 10_000, STABLE_END, TOTAL_STEPS}, ckpt_dir=CKPT_DIR,
66
+ log=LOG_DIR / "train.jsonl", status=ROOT / "STATUS.json", plot=OUT_DIR / "loss.png"),
67
+ "smoke": dict(data_dir=ROOT / "data" / "pilot", max_blocks=29_297, steps=200, ckpt_every=100, eval_every=100,
68
+ plot_every=200, milestones=set(), ckpt_dir=OUT_DIR / "smoke" / "ckpt",
69
+ log=LOG_DIR / "smoke.jsonl", status=OUT_DIR / "smoke" / "STATUS.json",
70
+ plot=OUT_DIR / "smoke" / "loss.png"),
71
+ }
72
+
73
+
74
+ def now() -> str:
75
+ return datetime.now().astimezone().isoformat(timespec="seconds")
76
+
77
+
78
+ def lr_at(step: int) -> float:
79
+ """WSD: linear warmup for 500 steps, constant until 15,872, linear decay to 1.8e-4 at 19,840."""
80
+ if step < WARMUP_STEPS:
81
+ return PEAK_LR * (step + 1) / WARMUP_STEPS
82
+ if step < STABLE_END:
83
+ return PEAK_LR
84
+ return PEAK_LR + (MIN_LR - PEAK_LR) * (step - STABLE_END) / (TOTAL_STEPS - STABLE_END)
85
+
86
+
87
+ class LossModel(torch.nn.Module):
88
+ """Model + next-token cross-entropy + z-loss in one module, so torch.compile fuses the fp32 logit math."""
89
+
90
+ def __init__(self, model: torch.nn.Module):
91
+ super().__init__()
92
+ self.model = model
93
+
94
+ def forward(self, x: torch.Tensor, y: torch.Tensor):
95
+ logits = self.model(input_ids=x, use_cache=False).logits.float()
96
+ lse = torch.logsumexp(logits, dim=-1)
97
+ ce = (lse - logits.gather(-1, y.unsqueeze(-1)).squeeze(-1)).mean()
98
+ return ce + Z_LOSS * lse.square().mean(), ce
99
+
100
+
101
+ def build_optimizer(model: torch.nn.Module) -> torch.optim.Optimizer:
102
+ """Weight decay only on 2D matrices; norms and the (tied) embedding get none."""
103
+ embed = model.model.embed_tokens.weight
104
+ decay = [p for p in model.parameters() if p.ndim == 2 and p is not embed]
105
+ no_decay = [p for p in model.parameters() if p.ndim != 2 or p is embed]
106
+ return torch.optim.AdamW([{"params": decay, "weight_decay": WEIGHT_DECAY},
107
+ {"params": no_decay, "weight_decay": 0.0}],
108
+ lr=PEAK_LR, betas=BETAS, eps=EPS, fused=True)
109
+
110
+
111
+ class BlockSampler:
112
+ """Deterministic batches: a seeded permutation of all blocks, addressed by (data step, rank, micro-step).
113
+
114
+ Blocks are read with one pread each instead of mmap: on this machine the shards live on the NTFS drive behind
115
+ DrvFs (the WSL disk sits on an exFAT USB drive whose driver bugchecks when the disk grows), and DrvFs page
116
+ faults are far slower than a single read call.
117
+ """
118
+
119
+ def __init__(self, data_dir: Path, max_blocks: int | None):
120
+ index = json.loads((data_dir / "index.json").read_text())
121
+ self.fds = [os.open(data_dir / s["file"], os.O_RDONLY) for s in index["shards"]]
122
+ self.cum = np.cumsum([0] + [s["blocks"] for s in index["shards"]])
123
+ self.total = int(self.cum[-1]) if max_blocks is None else min(max_blocks, int(self.cum[-1]))
124
+ self.perm = np.random.default_rng(DATA_SEED).permutation(self.total)
125
+
126
+ def get(self, data_step: int, rank: int, micro: int, accum: int) -> tuple[torch.Tensor, bool]:
127
+ start = data_step * SEQS_PER_STEP + (rank * accum + micro) * MICRO_BATCH
128
+ ids = self.perm[np.arange(start, start + MICRO_BATCH) % self.total]
129
+ shard = np.searchsorted(self.cum, ids, side="right") - 1
130
+ offsets = (ids - self.cum[shard]) * SEQ
131
+ rows = np.empty((MICRO_BATCH, SEQ + 1), dtype=np.int64)
132
+ for i, (s, o) in enumerate(zip(shard, offsets)):
133
+ rows[i] = np.frombuffer(os.pread(self.fds[s], 2 * (SEQ + 1), 2 * int(o)), dtype=np.uint16)
134
+ return torch.from_numpy(rows).pin_memory(), start + MICRO_BATCH > self.total
135
+
136
+
137
+ class GpuMonitor(threading.Thread):
138
+ """Polls nvidia-smi in the background so logging never blocks on it."""
139
+
140
+ def __init__(self, every_s: float = 5.0):
141
+ super().__init__(daemon=True)
142
+ self.every_s = every_s
143
+ self.exe = shutil.which("nvidia-smi") or "/usr/lib/wsl/lib/nvidia-smi"
144
+ self.temps, self.used_mb = [None, None], [None, None]
145
+
146
+ def run(self) -> None:
147
+ while True:
148
+ try:
149
+ out = subprocess.run([self.exe, "--query-gpu=temperature.gpu,memory.used", "--format=csv,noheader,nounits"],
150
+ capture_output=True, text=True, timeout=30).stdout
151
+ rows = [[int(v) for v in line.split(",")] for line in out.strip().splitlines()]
152
+ self.temps, self.used_mb = [r[0] for r in rows], [r[1] for r in rows]
153
+ except Exception:
154
+ pass
155
+ time.sleep(self.every_s)
156
+
157
+
158
+ class RunLog:
159
+ def __init__(self, path: Path):
160
+ path.parent.mkdir(parents=True, exist_ok=True)
161
+ self.f = open(path, "a", encoding="utf-8")
162
+
163
+ def write(self, rec: dict) -> None:
164
+ self.f.write(json.dumps(rec) + "\n")
165
+ self.f.flush()
166
+ os.fsync(self.f.fileno()) # this machine has crashed under load; keep every logged line
167
+ print(json.dumps(rec), flush=True)
168
+
169
+ def event(self, name: str, **fields) -> None:
170
+ self.write({"event": name, "wall_clock": now(), **fields})
171
+
172
+
173
+ def latest_checkpoint(ckpt_dir: Path) -> Path | None:
174
+ paths = sorted(ckpt_dir.glob("step_*.pt"))
175
+ return paths[-1] if paths else None
176
+
177
+
178
+ def fsync_dir(path: Path) -> None:
179
+ try:
180
+ fd = os.open(path, os.O_RDONLY)
181
+ try:
182
+ os.fsync(fd)
183
+ finally:
184
+ os.close(fd)
185
+ except OSError: # DrvFs (NTFS through 9p) may refuse fsync on a directory; the file itself was synced
186
+ pass
187
+
188
+
189
+ def save_checkpoint(ckpt_dir: Path, model, opt, state: dict, milestones: set) -> Path:
190
+ """Atomic and durable: write + fsync a temp file, rename, fsync the directory."""
191
+ path = ckpt_dir / f"step_{state['step']:05d}.pt"
192
+ tmp = path.with_suffix(".pt.tmp")
193
+ with open(tmp, "wb") as f:
194
+ torch.save({"model": model.state_dict(), "optimizer": opt.state_dict(), "state": state,
195
+ "rng": {"torch": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state(),
196
+ "numpy": np.random.get_state()}}, f)
197
+ f.flush()
198
+ os.fsync(f.fileno())
199
+ os.replace(tmp, path)
200
+ fsync_dir(ckpt_dir)
201
+ steps = sorted(int(p.stem.removeprefix("step_")) for p in ckpt_dir.glob("step_*.pt"))
202
+ keep = set(steps[-KEEP_LAST:]) | (set(steps) & milestones)
203
+ for s in steps:
204
+ if s not in keep:
205
+ (ckpt_dir / f"step_{s:05d}.pt").unlink()
206
+ return path
207
+
208
+
209
+ def write_status(path: Path, **fields) -> None:
210
+ path.parent.mkdir(parents=True, exist_ok=True)
211
+ tmp = path.with_suffix(".json.tmp")
212
+ with open(tmp, "w") as f:
213
+ f.write(json.dumps({"updated": now(), **fields}, indent=2))
214
+ f.flush()
215
+ os.fsync(f.fileno())
216
+ os.replace(tmp, path)
217
+ fsync_dir(path.parent)
218
+
219
+
220
+ def measure_gpu_flops(device, n: int = 8192, iters: int = 10) -> float:
221
+ """Peak bf16 matmul throughput of this GPU in FLOPs/s (2·n³ per n×n product): the MFU denominator.
222
+ Measured rather than taken from a spec sheet, since consumer-card FP32 figures understate bf16 kernels."""
223
+ a = torch.randn(n, n, device=device, dtype=torch.bfloat16)
224
+ b = torch.randn(n, n, device=device, dtype=torch.bfloat16)
225
+ for _ in range(3):
226
+ a @ b
227
+ torch.cuda.synchronize(device)
228
+ t0 = time.perf_counter()
229
+ for _ in range(iters):
230
+ a @ b
231
+ torch.cuda.synchronize(device)
232
+ flops = 2 * n**3 * iters / (time.perf_counter() - t0)
233
+ del a, b
234
+ torch.cuda.empty_cache()
235
+ return flops
236
+
237
+
238
+ def compile_with_fallback(ddp: DDP, sampler: BlockSampler, state: dict, rank: int, accum: int, device, opt):
239
+ """Compile and warm up on one micro-batch (no grad sync); on error or > 10 min, every rank falls back to eager."""
240
+
241
+ def on_timeout(signum, frame):
242
+ raise TimeoutError(f"torch.compile exceeded {COMPILE_TIMEOUT_S}s")
243
+
244
+ compiled = torch.compile(ddp)
245
+ t0, ok, err = time.time(), 1, None
246
+ signal.signal(signal.SIGALRM, on_timeout)
247
+ signal.alarm(COMPILE_TIMEOUT_S)
248
+ try:
249
+ x, _ = sampler.get(state["step"] + state["data_skip"], rank, 0, accum)
250
+ x = x.to(device)
251
+ with ddp.no_sync():
252
+ with torch.autocast("cuda", dtype=torch.bfloat16):
253
+ loss, _ = compiled(x[:, :-1], x[:, 1:])
254
+ loss.backward()
255
+ torch.cuda.synchronize(device)
256
+ except Exception as e:
257
+ ok, err = 0, f"{type(e).__name__}: {e}"[:1000]
258
+ finally:
259
+ signal.alarm(0)
260
+ opt.zero_grad(set_to_none=True)
261
+ flag = torch.tensor([ok], device=device)
262
+ dist.all_reduce(flag, op=dist.ReduceOp.MIN)
263
+ if flag.item():
264
+ return compiled, "compile", time.time() - t0, None
265
+ torch._dynamo.reset()
266
+ return ddp, "eager", time.time() - t0, err or "compile failed on another rank"
267
+
268
+
269
+ def main() -> None:
270
+ ap = argparse.ArgumentParser()
271
+ ap.add_argument("--smoke", action="store_true", help="200-step smoke test on the pilot data")
272
+ ap.add_argument("--stop-at", type=int, help="exit cleanly once this step is reached (resume testing)")
273
+ args = ap.parse_args()
274
+ run_name = "smoke" if args.smoke else "train"
275
+ cfg = RUNS[run_name]
276
+
277
+ local_rank = int(os.environ["LOCAL_RANK"])
278
+ device = torch.device("cuda", local_rank)
279
+ torch.cuda.set_device(device)
280
+ dist.init_process_group("nccl", timeout=timedelta(minutes=30), device_id=device)
281
+ rank, world = dist.get_rank(), dist.get_world_size()
282
+ master = rank == 0
283
+ accum = SEQS_PER_STEP // (world * MICRO_BATCH)
284
+ assert accum * world * MICRO_BATCH == SEQS_PER_STEP, "tokens/step must stay 131,072"
285
+ torch.backends.cuda.matmul.allow_tf32 = True
286
+ torch.backends.cudnn.allow_tf32 = True
287
+
288
+ log = RunLog(cfg["log"]) if master else None
289
+
290
+ def event(name: str, **fields) -> None:
291
+ if master:
292
+ log.event(name, **fields)
293
+
294
+ torch.manual_seed(0)
295
+ raw = build_model().to(device)
296
+ n_params = sum(p.numel() for p in raw.parameters())
297
+ assert n_params == EXPECTED_PARAMS, f"param count {n_params:,} != {EXPECTED_PARAMS:,}"
298
+ opt = build_optimizer(raw)
299
+ state = {"step": 0, "data_skip": 0, "lr_scale": 1.0, "spikes": 0, "loss_hist": [], "alerts": [],
300
+ "last_val": None, "compile": None}
301
+ cfg["ckpt_dir"].mkdir(parents=True, exist_ok=True)
302
+ resume = latest_checkpoint(cfg["ckpt_dir"])
303
+ if resume:
304
+ ck = torch.load(resume, map_location=device, weights_only=False)
305
+ raw.load_state_dict(ck["model"])
306
+ opt.load_state_dict(ck["optimizer"])
307
+ state.update(ck["state"])
308
+ torch.set_rng_state(ck["rng"]["torch"].cpu()) # map_location moved it to the GPU; the CPU RNG needs it back
309
+ del ck
310
+ event("resume", checkpoint=resume.name, step=state["step"], data_skip=state["data_skip"],
311
+ lr_scale=state["lr_scale"], loss_guard_events=state["spikes"])
312
+ else:
313
+ event("start", run=run_name, params=n_params, world=world, micro_batch=MICRO_BATCH, grad_accum=accum,
314
+ tokens_per_step=TOKENS_PER_STEP, steps=cfg["steps"], torch=torch.__version__)
315
+
316
+ sampler = BlockSampler(cfg["data_dir"], cfg["max_blocks"])
317
+ peak = torch.tensor([measure_gpu_flops(device)], device=device, dtype=torch.float64)
318
+ peaks = [torch.zeros_like(peak) for _ in range(world)]
319
+ dist.all_gather(peaks, peak)
320
+ peak_flops = sum(p.item() for p in peaks)
321
+ event("gpu_flops", tflops_per_gpu=[round(p.item() / 1e12, 1) for p in peaks], kernel="bf16 matmul 8192x8192")
322
+
323
+ ddp = DDP(LossModel(raw), device_ids=[local_rank], gradient_as_bucket_view=True, broadcast_buffers=False)
324
+ runner, mode, compile_s, compile_err = compile_with_fallback(ddp, sampler, state, rank, accum, device, opt)
325
+ state["compile"] = mode
326
+ event("compile", mode=mode, seconds=round(compile_s, 1), **({"error": compile_err} if compile_err else {}))
327
+
328
+ if resume is None and master:
329
+ save_checkpoint(cfg["ckpt_dir"], raw, opt, state, cfg["milestones"]) # fallback for the loss guard
330
+ dist.barrier()
331
+
332
+ gpu = GpuMonitor() if master else None
333
+ if gpu:
334
+ gpu.start()
335
+ flops_per_token = 6 * n_params + 12 * raw.config.num_hidden_layers * raw.config.num_attention_heads \
336
+ * raw.config.head_dim * SEQ
337
+ step = state["step"]
338
+ step_times, window, all_dts = deque(maxlen=100), [], []
339
+ slow = hot = 0
340
+ wrapped_logged = False
341
+ mark_t, mark_step = time.time(), step
342
+ maxima = {"temp": [0, 0], "smi_mb": [0, 0], "peak_alloc": [0.0] * world, "peak_reserved": [0.0] * world}
343
+ init_loss = last_loss = None
344
+ lr = lr_at(step) * state["lr_scale"]
345
+
346
+ def status(state_label: str) -> None:
347
+ if not master:
348
+ return
349
+ hist = state["loss_hist"]
350
+ sec_per_step = (time.time() - mark_t) / max(step - mark_step, 1)
351
+ tok_s = TOKENS_PER_STEP * len(step_times) / sum(step_times) if step_times else None
352
+ write_status(cfg["status"], run=run_name, state=state_label, step=step, total_steps=cfg["steps"],
353
+ percent=round(100 * step / cfg["steps"], 2),
354
+ loss_smoothed=round(sum(hist) / len(hist), 4) if hist else None,
355
+ tok_s=round(tok_s) if tok_s else None, lr=lr, lr_scale=state["lr_scale"],
356
+ eta_hours=round((cfg["steps"] - step) * sec_per_step / 3600, 2),
357
+ eta_at=datetime.fromtimestamp(time.time() + (cfg["steps"] - step) * sec_per_step)
358
+ .astimezone().isoformat(timespec="minutes"),
359
+ tokens_seen=step * TOKENS_PER_STEP, data_skip_steps=state["data_skip"],
360
+ loss_guard_events=state["spikes"], compile=mode, last_val=state["last_val"],
361
+ alerts=state["alerts"][-20:])
362
+
363
+ def alert(kind: str, message: str, **fields) -> None:
364
+ if master:
365
+ rec = {"kind": kind, "step": step, "message": message, "wall_clock": now(), **fields}
366
+ state["alerts"].append(rec)
367
+ log.write({"event": "alert", **rec})
368
+ status("training")
369
+
370
+ def stop(reason: str, code: int) -> None:
371
+ event("stopped", step=step, reason=reason)
372
+ status(f"stopped: {reason}")
373
+ dist.destroy_process_group()
374
+ raise SystemExit(code)
375
+
376
+ while step < cfg["steps"] and (args.stop_at is None or step < args.stop_at):
377
+ lr = lr_at(step) * state["lr_scale"]
378
+ for group in opt.param_groups:
379
+ group["lr"] = lr
380
+ t0 = time.perf_counter()
381
+ acc = torch.zeros(2, device=device)
382
+ for micro in range(accum):
383
+ x, wrapped = sampler.get(step + state["data_skip"], rank, micro, accum)
384
+ if wrapped and not wrapped_logged:
385
+ event("data_wrap", step=step, blocks=sampler.total)
386
+ wrapped_logged = True
387
+ x = x.to(device, non_blocking=True)
388
+ with ddp.no_sync() if micro < accum - 1 else nullcontext():
389
+ with torch.autocast("cuda", dtype=torch.bfloat16):
390
+ loss, ce = runner(x[:, :-1], x[:, 1:])
391
+ (loss / accum).backward()
392
+ acc += torch.stack([ce.detach(), loss.detach()]) / accum
393
+ dist.all_reduce(acc, op=dist.ReduceOp.AVG)
394
+ ce_val, loss_val = acc.tolist()
395
+
396
+ hist = state["loss_hist"]
397
+ moving_avg = sum(hist) / len(hist) if hist else None
398
+ if not math.isfinite(ce_val) or (len(hist) >= SPIKE_WINDOW and ce_val > moving_avg + SPIKE_DELTA):
399
+ state["spikes"] += 1
400
+ event("loss_guard", step=step, loss=ce_val, moving_avg=moving_avg, count=state["spikes"])
401
+ if state["spikes"] >= MAX_SPIKES:
402
+ stop(f"loss guard triggered {MAX_SPIKES} times", 3)
403
+ path = latest_checkpoint(cfg["ckpt_dir"])
404
+ ck = torch.load(path, map_location=device, weights_only=False)
405
+ raw.load_state_dict(ck["model"])
406
+ opt.load_state_dict(ck["optimizer"])
407
+ keep = {k: state[k] for k in ("spikes", "alerts", "compile")}
408
+ skip, scale = state["data_skip"], state["lr_scale"]
409
+ state.update(ck["state"])
410
+ state.update(keep, data_skip=skip + SPIKE_SKIP_STEPS, lr_scale=scale * 0.5)
411
+ del ck
412
+ opt.zero_grad(set_to_none=True)
413
+ step = state["step"]
414
+ event("reload", checkpoint=path.name, step=step, data_skip=state["data_skip"], lr_scale=state["lr_scale"])
415
+ continue
416
+ if step == 0:
417
+ init_loss = ce_val
418
+ event("init_loss", loss=round(ce_val, 4), expected=round(math.log(raw.config.vocab_size), 4))
419
+ if not INIT_LOSS_RANGE[0] <= ce_val <= INIT_LOSS_RANGE[1]:
420
+ stop(f"step-0 loss {ce_val:.3f} outside {INIT_LOSS_RANGE}: init or target shift is wrong", 2)
421
+
422
+ grad_norm = torch.nn.utils.clip_grad_norm_(raw.parameters(), GRAD_CLIP)
423
+ opt.step()
424
+ opt.zero_grad(set_to_none=True)
425
+ step += 1
426
+ state["step"] = step
427
+ hist.append(ce_val)
428
+ del hist[:-SPIKE_WINDOW]
429
+ last_loss = ce_val
430
+ dt = time.perf_counter() - t0
431
+ step_times.append(dt)
432
+ window.append(dt)
433
+ all_dts.append(dt)
434
+
435
+ if master:
436
+ slow = slow + 1 if TOKENS_PER_STEP / dt < MIN_TOK_S else 0
437
+ if slow == SLOW_STEPS:
438
+ alert("throughput", f"tok/s below {MIN_TOK_S:,} for {SLOW_STEPS} consecutive steps (I/O or thermal?)",
439
+ tok_s=round(TOKENS_PER_STEP * len(step_times) / sum(step_times)), temps=gpu.temps)
440
+
441
+ if step % LOG_EVERY == 0:
442
+ mem = torch.tensor([torch.cuda.memory_allocated(device), torch.cuda.max_memory_allocated(device),
443
+ torch.cuda.max_memory_reserved(device)], device=device, dtype=torch.float64) / 2**30
444
+ mems = [torch.zeros_like(mem) for _ in range(world)]
445
+ dist.all_gather(mems, mem)
446
+ if master:
447
+ tok_s = TOKENS_PER_STEP * len(window) / sum(window)
448
+ temps = gpu.temps
449
+ log.write({"step": step, "loss": round(ce_val, 4), "loss_total": round(loss_val, 4), "lr": lr,
450
+ "grad_norm": round(grad_norm.item(), 4), "tokens_seen": step * TOKENS_PER_STEP,
451
+ "tok_s": round(tok_s), "mfu": round(flops_per_token * tok_s / peak_flops, 4),
452
+ "gpu0_temp": temps[0], "gpu1_temp": temps[1] if len(temps) > 1 else None,
453
+ "mem_alloc": [round(m[0].item(), 2) for m in mems],
454
+ "mem_peak": [round(m[1].item(), 2) for m in mems], "wall_clock": now()})
455
+ for i, t in enumerate(temps):
456
+ if t is not None:
457
+ maxima["temp"][i] = max(maxima["temp"][i], t)
458
+ for i, used in enumerate(gpu.used_mb):
459
+ if used is not None:
460
+ maxima["smi_mb"][i] = max(maxima["smi_mb"][i], used)
461
+ maxima["peak_alloc"] = [round(m[1].item(), 2) for m in mems]
462
+ maxima["peak_reserved"] = [round(m[2].item(), 2) for m in mems]
463
+ hot = hot + LOG_EVERY if any(t is not None and t > HOT_C for t in temps) else 0
464
+ if hot == HOT_STEPS:
465
+ alert("thermal", f"GPU above {HOT_C}°C for {HOT_STEPS} steps (training continues)", temps=temps)
466
+ window = []
467
+
468
+ if step % cfg["eval_every"] == 0 or step == cfg["steps"]:
469
+ results = val_losses(raw, device, rank, world)
470
+ if master:
471
+ state["last_val"] = {"step": step, **{d: {k: round(v, 4) for k, v in r.items()}
472
+ for d, r in results.items()}}
473
+ log.write({"event": "eval", "wall_clock": now(), **state["last_val"]})
474
+
475
+ if step % cfg["ckpt_every"] == 0 or step in cfg["milestones"] or step == cfg["steps"]:
476
+ if master:
477
+ path = save_checkpoint(cfg["ckpt_dir"], raw, opt, state, cfg["milestones"])
478
+ event("checkpoint", step=step, file=path.name)
479
+ status("training")
480
+ dist.barrier()
481
+
482
+ if master and (step % cfg["plot_every"] == 0 or step == cfg["steps"]):
483
+ try:
484
+ plot_loss(cfg["log"], cfg["plot"], cfg["steps"])
485
+ except Exception as e: # a plotting bug must never kill the run
486
+ event("plot_error", error=f"{type(e).__name__}: {e}")
487
+
488
+ if step >= cfg["steps"]:
489
+ event("finished", step=step, hours=round((time.time() - mark_t) / 3600, 2))
490
+ status("finished")
491
+ else:
492
+ event("stopped_at", step=step)
493
+ status(f"stopped at step {step} (--stop-at)")
494
+
495
+ if master and args.smoke:
496
+ steady = all_dts[20:] or all_dts
497
+ mean_dt = sum(steady) / len(steady)
498
+ summary = {"params": n_params, "compile": mode, "compile_seconds": round(compile_s, 1),
499
+ "compile_error": compile_err, "init_loss": init_loss, "last_step": step, "loss_at_last_step": last_loss,
500
+ "tok_s_mean": round(TOKENS_PER_STEP / mean_dt), "sec_per_step": round(mean_dt, 3),
501
+ "eta_full_run_hours": round(TOTAL_STEPS * mean_dt / 3600, 2),
502
+ "peak_mem_alloc_gb": maxima["peak_alloc"], "peak_mem_reserved_gb": maxima["peak_reserved"],
503
+ "nvidia_smi_used_mb_max": maxima["smi_mb"], "temp_max_c": maxima["temp"],
504
+ "last_val": state["last_val"]}
505
+ (OUT_DIR / "smoke" / "summary.json").write_text(json.dumps(summary, indent=2))
506
+ event("smoke_summary", **summary)
507
+ dist.destroy_process_group()
508
+
509
+
510
+ if __name__ == "__main__":
511
+ main()
scripts/train_tokenizer.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Train the GPT-U-20M tokenizer: byte-level BPE, 16,384 vocab, on ~2 GB of text sampled in the 45/35/20 mix.
2
+
3
+ Stages (finished stages are skipped on re-run):
4
+ 1. corpus -> data/tok_corpus/<stream>.jsonl (training files) + <stream>.holdout.jsonl (holdout files)
5
+ 2. train -> tokenizer/
6
+ 3. validate -> logs/tokenizer_report.json: fertility per domain, round-trip on 1000 samples
7
+ """
8
+ import json
9
+ import multiprocessing as mp
10
+ import random
11
+ import time
12
+ from concurrent.futures import ProcessPoolExecutor
13
+
14
+ from tokenizers import Regex, Tokenizer, decoders, models, pre_tokenizers, trainers
15
+ from transformers import PreTrainedTokenizerFast
16
+
17
+ from common import LOG_DIR, ROOT, TOKENIZER_DIR
18
+ from sources import STREAM_DOMAIN, STREAM_SHARE, STREAMS, file_splits, open_stream
19
+
20
+ EOT = "<|endoftext|>"
21
+ VOCAB_SIZE = 16384
22
+ CORPUS_BYTES = 2_000_000_000
23
+ HOLDOUT_DOCS = 1000
24
+ CORPUS_DIR = ROOT / "data" / "tok_corpus"
25
+ SPLITS_PATH = ROOT / "data" / "file_splits.json"
26
+ # cl100k-style split: whitespace runs stay whole pre-tokens (Python indentation), digits handled by Digits below.
27
+ SPLIT_PATTERN = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
28
+
29
+
30
+ def log(msg: str) -> None:
31
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
32
+
33
+
34
+ def collect(name: str, files: list[str], byte_budget: float, max_docs: float, out_name: str):
35
+ out_path = CORPUS_DIR / out_name
36
+ tmp = out_path.with_suffix(".tmp")
37
+ n_docs = n_bytes = 0
38
+ t0 = time.time()
39
+ with open(tmp, "w", encoding="utf-8") as f:
40
+ for row in open_stream(name, files):
41
+ f.write(json.dumps({"text": row["text"]}, ensure_ascii=False) + "\n")
42
+ n_docs += 1
43
+ n_bytes += len(row["text"].encode("utf-8"))
44
+ if n_bytes >= byte_budget or n_docs >= max_docs:
45
+ break
46
+ if n_docs % 50_000 == 0:
47
+ log(f" {out_name}: {n_docs:,} docs, {n_bytes / 1e6:,.0f} MB ({n_bytes / 1e6 / (time.time() - t0):.1f} MB/s)")
48
+ tmp.replace(out_path)
49
+ return out_name, n_docs, n_bytes, time.time() - t0
50
+
51
+
52
+ def build_corpus(splits: dict) -> None:
53
+ CORPUS_DIR.mkdir(parents=True, exist_ok=True)
54
+ jobs = []
55
+ for name in STREAMS:
56
+ part = splits[STREAM_DOMAIN[name]]
57
+ jobs.append((name, part["train"], STREAM_SHARE[name] * CORPUS_BYTES, float("inf"), f"{name}.jsonl"))
58
+ jobs.append((name, part["holdout"], float("inf"), HOLDOUT_DOCS, f"{name}.holdout.jsonl"))
59
+ pending = [j for j in jobs if not (CORPUS_DIR / j[-1]).exists()]
60
+ log(f"corpus: {len(pending)} of {len(jobs)} files to collect")
61
+ t0 = time.time()
62
+ with ProcessPoolExecutor(max_workers=4, mp_context=mp.get_context("spawn")) as ex:
63
+ for out_name, n_docs, n_bytes, secs in ex.map(collect, *zip(*pending)) if pending else []:
64
+ log(f" done {out_name}: {n_docs:,} docs, {n_bytes / 1e6:,.1f} MB in {secs / 60:.1f} min")
65
+ log(f"corpus ready in {(time.time() - t0) / 60:.1f} min")
66
+
67
+
68
+ def read_texts(out_name: str, limit: int | None = None) -> list[str]:
69
+ texts = []
70
+ with open(CORPUS_DIR / out_name, encoding="utf-8") as f:
71
+ for line in f:
72
+ texts.append(json.loads(line)["text"])
73
+ if limit and len(texts) >= limit:
74
+ break
75
+ return texts
76
+
77
+
78
+ def batches(out_names: list[str], size: int = 1000):
79
+ buf = []
80
+ for out_name in out_names:
81
+ with open(CORPUS_DIR / out_name, encoding="utf-8") as f:
82
+ for line in f:
83
+ buf.append(json.loads(line)["text"])
84
+ if len(buf) == size:
85
+ yield buf
86
+ buf = []
87
+ if buf:
88
+ yield buf
89
+
90
+
91
+ def build_tokenizer() -> Tokenizer:
92
+ tok = Tokenizer(models.BPE(byte_fallback=True))
93
+ tok.pre_tokenizer = pre_tokenizers.Sequence([
94
+ pre_tokenizers.Split(Regex(SPLIT_PATTERN), behavior="isolated"),
95
+ pre_tokenizers.Digits(individual_digits=True),
96
+ pre_tokenizers.ByteLevel(add_prefix_space=False, use_regex=False),
97
+ ])
98
+ tok.decoder = decoders.ByteLevel()
99
+ return tok
100
+
101
+
102
+ def train() -> None:
103
+ tok = build_tokenizer()
104
+ trainer = trainers.BpeTrainer(vocab_size=VOCAB_SIZE, special_tokens=[EOT],
105
+ initial_alphabet=pre_tokenizers.ByteLevel.alphabet(), show_progress=False)
106
+ t0 = time.time()
107
+ tok.train_from_iterator(batches([f"{name}.jsonl" for name in STREAMS]), trainer=trainer)
108
+ log(f"BPE trained in {(time.time() - t0) / 60:.1f} min, vocab {tok.get_vocab_size()}")
109
+ TOKENIZER_DIR.mkdir(parents=True, exist_ok=True)
110
+ hf_tok = PreTrainedTokenizerFast(tokenizer_object=tok, bos_token=EOT, eos_token=EOT, pad_token=EOT,
111
+ model_max_length=1024, clean_up_tokenization_spaces=False)
112
+ hf_tok.save_pretrained(TOKENIZER_DIR)
113
+
114
+
115
+ EDGE_CASES = [
116
+ "def f(x):\n\tif x:\n\t\treturn x\n\treturn None\n",
117
+ "class A:\n def __init__(self):\n self.x = 1\n\n\n def run(self): # comment\n pass\n",
118
+ " four\n eight\n\t\ttabs\n \t mixed \t\n",
119
+ "line1\r\nline2\r\n\r\nline3\rline4",
120
+ "Olá, ação, coração — “aspas” ‘simples’ … não é?",
121
+ "日本語のテキスト、中文文本,한국어 텍스트",
122
+ "emoji 👍🏽 👨‍👩‍👧‍👦 🇧🇷 ❤️",
123
+ "مرحبا بالعالم שלום עולם",
124
+ "combining: e\u0301 a\u0308 n\u0303",
125
+ "zero-width:\u200b\u200c\u200d\ufeff end",
126
+ "numbers 1234567890 3.14159 -0.0001 1e-10 0xFF 000123",
127
+ " leading and trailing spaces ",
128
+ "\n\n\n\t\t\t\n",
129
+ "",
130
+ " ",
131
+ "control \x00\x01\x1f\x7f chars",
132
+ "math ∑∫√∞≠≤≥ αβγ ℝ²",
133
+ "<|endoftext|> literal special token <|endoftext|>",
134
+ "a" * 5000,
135
+ " " * 300 + "x",
136
+ ]
137
+ RANGES = [(0x20, 0x7E), (0xA0, 0x24F), (0x370, 0x3FF), (0x400, 0x4FF), (0x590, 0x6FF), (0x900, 0x97F),
138
+ (0x3040, 0x30FF), (0x4E00, 0x4FFF), (0xAC00, 0xAD00), (0x2000, 0x206F), (0x2200, 0x22FF),
139
+ (0x1F300, 0x1F64F), (0x1F900, 0x1F9FF)]
140
+ WHITESPACE = [" ", " ", " ", "\t", "\t\t", "\n", "\r\n", "\n\n", "\u00a0", "\u3000", "\n ", "\n\t"]
141
+
142
+
143
+ def synthetic(n: int, rng: random.Random) -> list[str]:
144
+ out = list(EDGE_CASES)
145
+ while len(out) < n:
146
+ parts = []
147
+ for _ in range(rng.randint(5, 60)):
148
+ r = rng.random()
149
+ if r < 0.3:
150
+ parts.append(rng.choice(WHITESPACE))
151
+ elif r < 0.4:
152
+ parts.append(rng.choice(EDGE_CASES))
153
+ else:
154
+ lo, hi = rng.choice(RANGES)
155
+ parts.append("".join(chr(rng.randint(lo, hi)) for _ in range(rng.randint(1, 8))))
156
+ out.append("".join(parts))
157
+ return out[:n]
158
+
159
+
160
+ def fertility(tok: Tokenizer, texts: list[str]) -> dict:
161
+ n_tok = sum(len(e.ids) for e in tok.encode_batch(texts))
162
+ n_words = sum(len(t.split()) for t in texts)
163
+ n_bytes = sum(len(t.encode("utf-8")) for t in texts)
164
+ return {"docs": len(texts), "tokens": n_tok, "tokens_per_word": round(n_tok / n_words, 4),
165
+ "bytes_per_token": round(n_bytes / n_tok, 4)}
166
+
167
+
168
+ def validate() -> dict:
169
+ tok = Tokenizer.from_file(str(TOKENIZER_DIR / "tokenizer.json"))
170
+ hf_tok = PreTrainedTokenizerFast.from_pretrained(TOKENIZER_DIR)
171
+ held = {name: read_texts(f"{name}.holdout.jsonl") for name in STREAMS}
172
+ n_py = round(HOLDOUT_DOCS * 0.27)
173
+ code_mix = held["code_py"][:n_py] + held["code_other"][:HOLDOUT_DOCS - n_py]
174
+
175
+ report = {
176
+ "vocab_size": tok.get_vocab_size(),
177
+ "eot_id": tok.token_to_id(EOT),
178
+ "fits_uint16": tok.get_vocab_size() <= 65535,
179
+ "fertility": {
180
+ "dclm": fertility(tok, held["dclm"]),
181
+ "edu": fertility(tok, held["edu"]),
182
+ "code": fertility(tok, code_mix),
183
+ "code_python_only": fertility(tok, held["code_py"]),
184
+ },
185
+ }
186
+
187
+ rng = random.Random(0)
188
+ code_all = held["code_py"] + held["code_other"]
189
+ rng.shuffle(code_all)
190
+ tabbed = [t for t in code_all if "\t" in t][:150]
191
+ plain = [t for t in code_all if "\t" not in t][:300 - len(tabbed)]
192
+ samples = held["dclm"][:300] + held["edu"][:300] + tabbed + plain + synthetic(100, rng)
193
+ raw_fail = [i for i, s in enumerate(samples) if tok.decode(tok.encode(s).ids, skip_special_tokens=False) != s]
194
+ hf_fail = [i for i, s in enumerate(samples)
195
+ if hf_tok.decode(hf_tok.encode(s, add_special_tokens=False), skip_special_tokens=False,
196
+ clean_up_tokenization_spaces=False) != s]
197
+ report["round_trip"] = {
198
+ "samples": len(samples),
199
+ "with_tabs": sum("\t" in s for s in samples),
200
+ "non_ascii": sum(not s.isascii() for s in samples),
201
+ "failures_tokenizers": len(raw_fail),
202
+ "failures_transformers": len(hf_fail),
203
+ "first_failures": [repr(samples[i][:120]) for i in (raw_fail + hf_fail)[:5]],
204
+ }
205
+ example = "def f(x):\n return x\n\t\tpass # 2024"
206
+ report["example_tokens"] = tok.encode(example).tokens
207
+ return report
208
+
209
+
210
+ def main() -> None:
211
+ splits = file_splits(SPLITS_PATH)
212
+ log("holdout files: " + ", ".join(f"{d}={v['holdout'][0]}" for d, v in splits.items()))
213
+ build_corpus(splits)
214
+ if (TOKENIZER_DIR / "tokenizer.json").exists():
215
+ log("tokenizer already trained, skipping")
216
+ else:
217
+ train()
218
+ report = validate()
219
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
220
+ (LOG_DIR / "tokenizer_report.json").write_text(json.dumps(report, indent=2, ensure_ascii=False))
221
+ log(json.dumps(report, indent=2, ensure_ascii=False))
222
+
223
+
224
+ if __name__ == "__main__":
225
+ main()
scripts/watch_train.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Block until the training tmux session ends or the run logs something that needs attention
3
+ # (alert, loss_guard, reload, stopped, data_wrap); then print those events and STATUS.json.
4
+ # SESSION=gptu LOG=logs/train.jsonl scripts/watch_train.sh
5
+ cd "$(dirname "$0")/.."
6
+ SESSION=${SESSION:-gptu}
7
+ LOG=${LOG:-logs/train.jsonl}
8
+ PATTERN='"event": "(alert|loss_guard|reload|stopped|data_wrap)"'
9
+ count() { grep -acE "$PATTERN" "$LOG" 2>/dev/null || true; }
10
+ seen=$(count); seen=${seen:-0}
11
+ for _ in $(seq 1 60); do tmux has-session -t "$SESSION" 2>/dev/null && break; sleep 2; done
12
+ while tmux has-session -t "$SESSION" 2>/dev/null; do
13
+ n=$(count); n=${n:-0}
14
+ if [ "$n" -gt "$seen" ]; then
15
+ echo "=== attention: $((n - seen)) new event(s) at $(date -Is) ==="
16
+ grep -aE "$PATTERN" "$LOG" | tail -n $((n - seen)) | cut -c1-600 || true
17
+ cat STATUS.json 2>/dev/null || true
18
+ exit 0
19
+ fi
20
+ sleep 60
21
+ done
22
+ echo "=== session $SESSION ended: $(date -Is) ==="
23
+ grep -a '"event"' "$LOG" 2>/dev/null | tail -12 | cut -c1-500 || true
24
+ cat STATUS.json 2>/dev/null || true
25
+ exit 0
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<|endoftext|>",
4
+ "clean_up_tokenization_spaces": false,
5
+ "eos_token": "<|endoftext|>",
6
+ "model_max_length": 1024,
7
+ "pad_token": "<|endoftext|>",
8
+ "tokenizer_class": "TokenizersBackend"
9
+ }