NorthernTribe-Research commited on
Commit
e69a71a
·
verified ·
1 Parent(s): 662bc81

Add tailored from-scratch training stack (tokenizer + random-init LM) for math conjecture solving

Browse files
README.md CHANGED
@@ -9,8 +9,7 @@ tags:
9
  - math-conjecture-solver
10
  - formal-math
11
  - lora
12
- base_model:
13
- - Qwen/Qwen2.5-Math-7B-Instruct
14
  datasets:
15
  - NorthernTribe-Research/math-conjecture-training-corpus
16
  ---
@@ -36,16 +35,19 @@ Do not treat outputs as final proof truth without formal verification.
36
 
37
  ## Training Stack
38
 
39
- This folder contains the training/evaluation stack that powers both local runs and the Hugging Face Space trainer.
 
 
 
 
 
40
 
41
- Included:
42
- - `configs/math_conjecture_sft.yaml`: single-stage SFT profile
43
- - `configs/math_conjecture_sota.yaml`: default 4-stage SOTA curriculum profile
44
- - `configs/qwen25_math_sota.yaml`: alternate SOTA profile
45
  - `scripts/train_sft.py`: single-stage LoRA/QLoRA SFT
46
- - `scripts/train_sota.py`: staged curriculum training with post-eval + gate + Hub publish
 
47
  - `scripts/eval_sota.py`: pass@k / exact / boxed / family-level metrics
48
- - `scripts/merge_and_push.py`: merge adapter to full weights and publish
49
 
50
  ## Quickstart
51
 
@@ -53,31 +55,39 @@ Included:
53
  .venv/bin/python -m pip install -r model_development/requirements.txt
54
  ```
55
 
56
- Run SFT:
57
 
58
  ```bash
59
- .venv/bin/python model_development/scripts/train_sft.py \
60
- --config model_development/configs/math_conjecture_sft.yaml
61
  ```
62
 
63
- Run full SOTA curriculum:
 
 
64
 
65
  ```bash
66
- .venv/bin/python model_development/scripts/train_sota.py \
67
- --config model_development/configs/math_conjecture_sota.yaml
 
68
  ```
69
 
70
- Run dry-run validation only:
71
 
72
  ```bash
73
- .venv/bin/python model_development/scripts/train_sota.py \
74
- --config model_development/configs/math_conjecture_sota.yaml \
75
- --start-stage 1 \
76
- --max-stages 1 \
 
 
 
 
 
77
  --dry-run
78
  ```
79
 
80
- Evaluate adapter:
81
 
82
  ```bash
83
  .venv/bin/python model_development/scripts/eval_sota.py \
@@ -88,19 +98,19 @@ Evaluate adapter:
88
  --max-samples 260
89
  ```
90
 
91
- ## Outputs
92
 
93
- - final adapter: `model_development/runs/math-conjecture-sota/final_adapter`
94
- - training summary: `model_development/runs/math-conjecture-sota/training_summary.json`
95
- - post-eval report: `model_development/runs/math-conjecture-sota/post_eval_report.json`
96
 
97
- ## Quality Gate
 
 
 
98
 
99
- Promotion is blocked unless configured thresholds pass:
100
- - minimum evaluated rows,
101
- - `pass@1` and `pass@k`,
102
- - required family-level `pass@k`,
103
- - optional max final-stage eval loss.
104
 
105
  ## Auth
106
 
 
9
  - math-conjecture-solver
10
  - formal-math
11
  - lora
12
+ - from-scratch
 
13
  datasets:
14
  - NorthernTribe-Research/math-conjecture-training-corpus
15
  ---
 
35
 
36
  ## Training Stack
37
 
38
+ Included configs:
39
+ - `configs/math_conjecture_sft.yaml`: single-stage LoRA SFT profile
40
+ - `configs/math_conjecture_sota.yaml`: default 4-stage LoRA SOTA curriculum
41
+ - `configs/qwen25_math_sota.yaml`: alternate LoRA SOTA profile
42
+ - `configs/math_conjecture_scratch.yaml`: full from-scratch profile (tokenizer + random-init LM)
43
+ - `configs/math_conjecture_scratch_smoke.yaml`: lightweight scratch smoke-test profile
44
 
45
+ Included scripts:
 
 
 
46
  - `scripts/train_sft.py`: single-stage LoRA/QLoRA SFT
47
+ - `scripts/train_sota.py`: staged curriculum LoRA training + post-eval + quality gate
48
+ - `scripts/train_scratch.py`: from-scratch tokenizer training + random-init model training
49
  - `scripts/eval_sota.py`: pass@k / exact / boxed / family-level metrics
50
+ - `scripts/merge_and_push.py`: merge LoRA adapter to full weights and publish
51
 
52
  ## Quickstart
53
 
 
55
  .venv/bin/python -m pip install -r model_development/requirements.txt
56
  ```
57
 
58
+ ### Option A: LoRA SOTA (current default)
59
 
60
  ```bash
61
+ .venv/bin/python model_development/scripts/train_sota.py \
62
+ --config model_development/configs/math_conjecture_sota.yaml
63
  ```
64
 
65
+ ### Option B: From Scratch (tailored model)
66
+
67
+ Initialize tokenizer + model weights from scratch (no training yet):
68
 
69
  ```bash
70
+ .venv/bin/python model_development/scripts/train_scratch.py \
71
+ --config model_development/configs/math_conjecture_scratch.yaml \
72
+ --init-only
73
  ```
74
 
75
+ Full scratch training:
76
 
77
  ```bash
78
+ .venv/bin/python model_development/scripts/train_scratch.py \
79
+ --config model_development/configs/math_conjecture_scratch.yaml
80
+ ```
81
+
82
+ Fast local smoke check:
83
+
84
+ ```bash
85
+ .venv/bin/python model_development/scripts/train_scratch.py \
86
+ --config model_development/configs/math_conjecture_scratch_smoke.yaml \
87
  --dry-run
88
  ```
89
 
90
+ ## Evaluate
91
 
92
  ```bash
93
  .venv/bin/python model_development/scripts/eval_sota.py \
 
98
  --max-samples 260
99
  ```
100
 
101
+ For scratch checkpoints (no adapter), point `--base-model` to the checkpoint directory and omit `--adapter-path`.
102
 
103
+ ## Outputs
 
 
104
 
105
+ LoRA outputs:
106
+ - `model_development/runs/math-conjecture-sota/final_adapter`
107
+ - `model_development/runs/math-conjecture-sota/training_summary.json`
108
+ - `model_development/runs/math-conjecture-sota/post_eval_report.json`
109
 
110
+ Scratch outputs:
111
+ - `model_development/runs/math-conjecture-scratch/tokenizer/`
112
+ - `model_development/runs/math-conjecture-scratch/checkpoints/`
113
+ - `model_development/runs/math-conjecture-scratch/scratch_init_summary.json`
 
114
 
115
  ## Auth
116
 
configs/math_conjecture_scratch.yaml ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ global:
2
+ output_root: model_development/runs/math-conjecture-scratch
3
+ seed: 17
4
+
5
+ tokenizer:
6
+ tokenizer_dir: model_development/runs/math-conjecture-scratch/tokenizer
7
+ vocab_size: 32768
8
+ min_frequency: 2
9
+ max_train_rows: 220000
10
+ special_tokens:
11
+ - <pad>
12
+ - <unk>
13
+ - <s>
14
+ - </s>
15
+ - <|system|>
16
+ - <|user|>
17
+ - <|assistant|>
18
+
19
+ model:
20
+ n_layer: 12
21
+ n_head: 12
22
+ n_embd: 768
23
+ n_positions: 2048
24
+ use_bf16: true
25
+ resid_pdrop: 0.1
26
+ embd_pdrop: 0.1
27
+ attn_pdrop: 0.1
28
+ initializer_range: 0.02
29
+
30
+ data:
31
+ train_file: data/releases/v1/train.parquet
32
+ validation_file: data/releases/v1/validation.parquet
33
+ prompt_field: prompt
34
+ target_field: target
35
+ final_answer_field: final_answer
36
+ proof_field: proof_formal
37
+ max_seq_length: 2048
38
+ max_train_samples: 240000
39
+ max_eval_samples: 4500
40
+ system_prompt: |
41
+ You are NorthernTribe Research's math-conjecture solver.
42
+ Recover answers for solved conjectures, produce checkable reasoning, and
43
+ preserve formal consistency suitable for Lean verification.
44
+
45
+ training:
46
+ output_dir: model_development/runs/math-conjecture-scratch/checkpoints
47
+ num_train_epochs: 1
48
+ max_steps: null
49
+ per_device_train_batch_size: 1
50
+ per_device_eval_batch_size: 1
51
+ gradient_accumulation_steps: 32
52
+ learning_rate: 2.0e-4
53
+ weight_decay: 0.1
54
+ warmup_ratio: 0.03
55
+ lr_scheduler_type: cosine
56
+ max_grad_norm: 1.0
57
+ gradient_checkpointing: true
58
+ logging_steps: 10
59
+ save_steps: 250
60
+ eval_steps: 250
61
+ save_total_limit: 3
62
+ dataloader_num_workers: 2
63
+
64
+ hub:
65
+ push_to_hub: false
66
+ repo_id: NorthernTribe-Research/math-conjecture-model
67
+ private: false
68
+ commit_message: Upload scratch-trained math-conjecture solver model.
69
+
70
+ credentials:
71
+ path: huggingface-api-key.json
configs/math_conjecture_scratch_smoke.yaml ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ global:
2
+ output_root: model_development/runs/math-conjecture-scratch-smoke
3
+ seed: 17
4
+
5
+ tokenizer:
6
+ tokenizer_dir: model_development/runs/math-conjecture-scratch-smoke/tokenizer
7
+ vocab_size: 12000
8
+ min_frequency: 2
9
+ max_train_rows: 8000
10
+ special_tokens:
11
+ - <pad>
12
+ - <unk>
13
+ - <s>
14
+ - </s>
15
+ - <|system|>
16
+ - <|user|>
17
+ - <|assistant|>
18
+
19
+ model:
20
+ n_layer: 4
21
+ n_head: 4
22
+ n_embd: 256
23
+ n_positions: 1024
24
+ use_bf16: false
25
+ resid_pdrop: 0.1
26
+ embd_pdrop: 0.1
27
+ attn_pdrop: 0.1
28
+ initializer_range: 0.02
29
+
30
+ data:
31
+ train_file: data/releases/v1/train.parquet
32
+ validation_file: data/releases/v1/validation.parquet
33
+ prompt_field: prompt
34
+ target_field: target
35
+ final_answer_field: final_answer
36
+ proof_field: proof_formal
37
+ max_seq_length: 1024
38
+ max_train_samples: 5000
39
+ max_eval_samples: 500
40
+ system_prompt: |
41
+ You are NorthernTribe Research's math-conjecture solver.
42
+
43
+ training:
44
+ output_dir: model_development/runs/math-conjecture-scratch-smoke/checkpoints
45
+ num_train_epochs: 1
46
+ max_steps: 20
47
+ per_device_train_batch_size: 1
48
+ per_device_eval_batch_size: 1
49
+ gradient_accumulation_steps: 4
50
+ learning_rate: 3.0e-4
51
+ weight_decay: 0.05
52
+ warmup_ratio: 0.02
53
+ lr_scheduler_type: cosine
54
+ max_grad_norm: 1.0
55
+ gradient_checkpointing: false
56
+ logging_steps: 5
57
+ save_steps: 10
58
+ eval_steps: 10
59
+ save_total_limit: 2
60
+ dataloader_num_workers: 0
61
+
62
+ hub:
63
+ push_to_hub: false
64
+ repo_id: NorthernTribe-Research/math-conjecture-model
65
+ private: false
66
+ commit_message: Upload scratch-smoke math-conjecture solver artifacts.
67
+
68
+ credentials:
69
+ path: huggingface-api-key.json
requirements.txt CHANGED
@@ -9,3 +9,4 @@ gradio_client==2.1.0
9
  hf_transfer>=0.1.9
10
  pyyaml>=6.0.2
11
  sentencepiece>=0.2.0
 
 
9
  hf_transfer>=0.1.9
10
  pyyaml>=6.0.2
11
  sentencepiece>=0.2.0
12
+ tokenizers>=0.20.0
scripts/train_scratch.py ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Train a math-conjecture model from scratch (tokenizer + random-init LM)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ from typing import Any, Dict, Iterable, Optional, Tuple
11
+
12
+ import torch
13
+ import yaml
14
+ from datasets import Dataset, DatasetDict, load_dataset
15
+ from huggingface_hub import HfApi
16
+ from tokenizers import Tokenizer, decoders, models, normalizers, pre_tokenizers, processors, trainers
17
+ from transformers import (
18
+ DataCollatorForSeq2Seq,
19
+ GPT2Config,
20
+ GPT2LMHeadModel,
21
+ PreTrainedTokenizerFast,
22
+ Trainer,
23
+ TrainingArguments,
24
+ set_seed,
25
+ )
26
+
27
+ DEFAULT_CONFIG_PATH = Path("model_development/configs/math_conjecture_scratch.yaml")
28
+
29
+
30
+ def parse_args() -> argparse.Namespace:
31
+ parser = argparse.ArgumentParser(
32
+ description="Build tokenizer and train a random-init math-conjecture solver model from scratch."
33
+ )
34
+ parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG_PATH, help="YAML config path.")
35
+ parser.add_argument("--output-root", type=Path, default=None, help="Override global.output_root.")
36
+ parser.add_argument("--repo-id", type=str, default=None, help="Override hub.repo_id.")
37
+ parser.add_argument("--max-train-samples", type=int, default=None, help="Optional train subset.")
38
+ parser.add_argument("--max-eval-samples", type=int, default=None, help="Optional eval subset.")
39
+ parser.add_argument("--tokenizer-max-rows", type=int, default=None, help="Override tokenizer.max_train_rows.")
40
+ parser.add_argument("--init-only", action="store_true", help="Only build tokenizer/model and save artifacts.")
41
+ parser.add_argument("--dry-run", action="store_true", help="Validate pipeline without running training.")
42
+ parser.add_argument("--push-to-hub", action="store_true", help="Force Hub push enabled.")
43
+ parser.add_argument("--no-push-to-hub", action="store_true", help="Force Hub push disabled.")
44
+ parser.add_argument("--credentials-path", type=Path, default=None, help="Override credentials.path.")
45
+ return parser.parse_args()
46
+
47
+
48
+ def as_text(value: Any) -> str:
49
+ if value is None:
50
+ return ""
51
+ if isinstance(value, str):
52
+ return value.strip()
53
+ return str(value).strip()
54
+
55
+
56
+ def as_int(value: Any, default: int) -> int:
57
+ if value is None:
58
+ return default
59
+ try:
60
+ return int(value)
61
+ except (TypeError, ValueError):
62
+ return default
63
+
64
+
65
+ def as_float(value: Any, default: float) -> float:
66
+ if value is None:
67
+ return default
68
+ try:
69
+ return float(value)
70
+ except (TypeError, ValueError):
71
+ return default
72
+
73
+
74
+ def load_config(path: Path) -> Dict[str, Any]:
75
+ if not path.exists():
76
+ raise FileNotFoundError(f"Config not found: {path}")
77
+ cfg = yaml.safe_load(path.read_text(encoding="utf-8"))
78
+ if not isinstance(cfg, dict):
79
+ raise ValueError(f"Invalid config format: {path}")
80
+ for key in ("global", "tokenizer", "model", "data", "training"):
81
+ if key not in cfg or not isinstance(cfg[key], dict):
82
+ raise ValueError(f"Config missing section: {key}")
83
+ cfg.setdefault("hub", {})
84
+ cfg.setdefault("credentials", {})
85
+ return cfg
86
+
87
+
88
+ def apply_overrides(cfg: Dict[str, Any], args: argparse.Namespace) -> None:
89
+ if args.output_root is not None:
90
+ cfg["global"]["output_root"] = str(args.output_root)
91
+ if args.max_train_samples is not None:
92
+ cfg["data"]["max_train_samples"] = args.max_train_samples
93
+ if args.max_eval_samples is not None:
94
+ cfg["data"]["max_eval_samples"] = args.max_eval_samples
95
+ if args.tokenizer_max_rows is not None:
96
+ cfg["tokenizer"]["max_train_rows"] = args.tokenizer_max_rows
97
+ if args.repo_id:
98
+ cfg.setdefault("hub", {})["repo_id"] = args.repo_id
99
+ if args.credentials_path is not None:
100
+ cfg.setdefault("credentials", {})["path"] = str(args.credentials_path)
101
+ if args.push_to_hub and args.no_push_to_hub:
102
+ raise ValueError("Cannot set both --push-to-hub and --no-push-to-hub.")
103
+ if args.push_to_hub:
104
+ cfg.setdefault("hub", {})["push_to_hub"] = True
105
+ if args.no_push_to_hub:
106
+ cfg.setdefault("hub", {})["push_to_hub"] = False
107
+
108
+
109
+ def resolve_auth(cfg: Dict[str, Any]) -> Tuple[Optional[str], Optional[str]]:
110
+ token = as_text(os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN")) or None
111
+ username = as_text(os.environ.get("HF_USERNAME")) or None
112
+
113
+ cred_path = as_text(cfg.get("credentials", {}).get("path"))
114
+ if cred_path:
115
+ path = Path(cred_path)
116
+ if path.exists():
117
+ data = json.loads(path.read_text(encoding="utf-8"))
118
+ if token is None:
119
+ token = as_text(data.get("key")) or None
120
+ if username is None:
121
+ username = as_text(data.get("username")) or None
122
+ return token, username
123
+
124
+
125
+ def load_raw_datasets(data_cfg: Dict[str, Any]) -> DatasetDict:
126
+ train_path = Path(as_text(data_cfg.get("train_file")))
127
+ valid_path = Path(as_text(data_cfg.get("validation_file")))
128
+ if not train_path.exists():
129
+ raise FileNotFoundError(f"Missing train split: {train_path}")
130
+ if not valid_path.exists():
131
+ raise FileNotFoundError(f"Missing validation split: {valid_path}")
132
+
133
+ splits: Dict[str, Dataset] = {}
134
+ files = {"train": str(train_path), "validation": str(valid_path)}
135
+ for split_name, split_path in files.items():
136
+ loaded = load_dataset("parquet", data_files={split_name: split_path})
137
+ if split_name in loaded:
138
+ splits[split_name] = loaded[split_name]
139
+ else:
140
+ splits[split_name] = next(iter(loaded.values()))
141
+ return DatasetDict(splits)
142
+
143
+
144
+ def maybe_select(dataset: Dataset, max_samples: Optional[int]) -> Dataset:
145
+ if max_samples is None:
146
+ return dataset
147
+ if max_samples <= 0:
148
+ raise ValueError("max_samples must be positive.")
149
+ if max_samples >= len(dataset):
150
+ return dataset
151
+ return dataset.select(range(max_samples))
152
+
153
+
154
+ def stringify_structured(value: Any) -> str:
155
+ if value is None:
156
+ return ""
157
+ if isinstance(value, str):
158
+ text = value.strip()
159
+ if not text:
160
+ return ""
161
+ try:
162
+ parsed = json.loads(text)
163
+ except json.JSONDecodeError:
164
+ return text
165
+ return json.dumps(parsed, ensure_ascii=False, sort_keys=True)
166
+ return json.dumps(value, ensure_ascii=False, sort_keys=True)
167
+
168
+
169
+ def build_user_block(row: Dict[str, Any], data_cfg: Dict[str, Any]) -> str:
170
+ prompt_field = as_text(data_cfg.get("prompt_field")) or "prompt"
171
+ prompt = as_text(row.get(prompt_field))
172
+ if not prompt:
173
+ prompt = "Solve the math task."
174
+
175
+ meta_fields = [
176
+ ("task_type", "Task type"),
177
+ ("family", "Family"),
178
+ ("difficulty", "Difficulty"),
179
+ ("source_dataset", "Source"),
180
+ ("status_as_of", "Status as of"),
181
+ ]
182
+ meta_lines = []
183
+ for key, label in meta_fields:
184
+ value = as_text(row.get(key))
185
+ if value:
186
+ meta_lines.append(f"{label}: {value}")
187
+
188
+ if not meta_lines:
189
+ return prompt
190
+ return f"{prompt}\n\nMetadata:\n" + "\n".join(meta_lines)
191
+
192
+
193
+ def build_answer_block(row: Dict[str, Any], data_cfg: Dict[str, Any]) -> str:
194
+ target_field = as_text(data_cfg.get("target_field")) or "target"
195
+ final_answer_field = as_text(data_cfg.get("final_answer_field")) or "final_answer"
196
+ proof_field = as_text(data_cfg.get("proof_field")) or "proof_formal"
197
+
198
+ sections = []
199
+ target_text = stringify_structured(row.get(target_field))
200
+ if target_text:
201
+ sections.append(f"Structured target:\n{target_text}")
202
+
203
+ final_answer = stringify_structured(row.get(final_answer_field))
204
+ if final_answer:
205
+ sections.append(f"Final answer:\n{final_answer}")
206
+
207
+ proof_text = stringify_structured(row.get(proof_field))
208
+ if proof_text:
209
+ sections.append(f"Formal proof snippet:\n{proof_text}")
210
+
211
+ if not sections:
212
+ sections.append("No structured target provided.")
213
+ return "\n\n".join(sections).strip()
214
+
215
+
216
+ def build_prompt_text(row: Dict[str, Any], data_cfg: Dict[str, Any]) -> str:
217
+ system_prompt = as_text(data_cfg.get("system_prompt"))
218
+ if not system_prompt:
219
+ system_prompt = (
220
+ "You are NorthernTribe Research's math-conjecture solver. "
221
+ "Produce rigorous, checkable reasoning."
222
+ )
223
+ user_block = build_user_block(row, data_cfg)
224
+ return (
225
+ "<|system|>\n"
226
+ f"{system_prompt}\n"
227
+ "<|user|>\n"
228
+ f"{user_block}\n"
229
+ "<|assistant|>\n"
230
+ )
231
+
232
+
233
+ def iter_tokenizer_corpus(dataset: Dataset, data_cfg: Dict[str, Any], max_rows: int) -> Iterable[str]:
234
+ total = min(max_rows, len(dataset))
235
+ for idx in range(total):
236
+ row = dataset[idx]
237
+ prompt = build_prompt_text(row, data_cfg)
238
+ answer = build_answer_block(row, data_cfg)
239
+ yield f"{prompt}{answer}"
240
+
241
+
242
+ def build_tokenizer(
243
+ train_dataset: Dataset,
244
+ tok_cfg: Dict[str, Any],
245
+ data_cfg: Dict[str, Any],
246
+ output_root: Path,
247
+ ) -> PreTrainedTokenizerFast:
248
+ vocab_size = max(2048, as_int(tok_cfg.get("vocab_size"), 32000))
249
+ min_frequency = max(1, as_int(tok_cfg.get("min_frequency"), 2))
250
+ max_rows = max(100, as_int(tok_cfg.get("max_train_rows"), len(train_dataset)))
251
+
252
+ default_specials = ["<pad>", "<unk>", "<s>", "</s>", "<|system|>", "<|user|>", "<|assistant|>"]
253
+ special_tokens_cfg = tok_cfg.get("special_tokens")
254
+ if isinstance(special_tokens_cfg, list) and special_tokens_cfg:
255
+ special_tokens = [as_text(token) for token in special_tokens_cfg if as_text(token)]
256
+ else:
257
+ special_tokens = default_specials
258
+ for token in default_specials:
259
+ if token not in special_tokens:
260
+ special_tokens.append(token)
261
+
262
+ tokenizer_dir_raw = as_text(tok_cfg.get("tokenizer_dir"))
263
+ if tokenizer_dir_raw:
264
+ tokenizer_dir = Path(tokenizer_dir_raw)
265
+ else:
266
+ tokenizer_dir = output_root / "tokenizer"
267
+ tokenizer_dir.mkdir(parents=True, exist_ok=True)
268
+
269
+ tokenizer = Tokenizer(models.BPE(unk_token="<unk>"))
270
+ tokenizer.normalizer = normalizers.Sequence([normalizers.NFKC()])
271
+ tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
272
+ tokenizer.decoder = decoders.ByteLevel()
273
+
274
+ trainer = trainers.BpeTrainer(
275
+ vocab_size=vocab_size,
276
+ min_frequency=min_frequency,
277
+ show_progress=True,
278
+ special_tokens=special_tokens,
279
+ )
280
+
281
+ print(
282
+ "Training tokenizer from scratch: "
283
+ f"rows={min(max_rows, len(train_dataset))} vocab_size={vocab_size} min_frequency={min_frequency}"
284
+ )
285
+ tokenizer.train_from_iterator(
286
+ iter_tokenizer_corpus(train_dataset, data_cfg, max_rows),
287
+ trainer=trainer,
288
+ length=min(max_rows, len(train_dataset)),
289
+ )
290
+
291
+ bos_id = tokenizer.token_to_id("<s>")
292
+ eos_id = tokenizer.token_to_id("</s>")
293
+ if bos_id is not None and eos_id is not None:
294
+ tokenizer.post_processor = processors.TemplateProcessing(
295
+ single="<s> $A </s>",
296
+ pair="<s> $A </s> <s> $B </s>",
297
+ special_tokens=[("<s>", bos_id), ("</s>", eos_id)],
298
+ )
299
+
300
+ tokenizer_json_path = tokenizer_dir / "tokenizer.json"
301
+ tokenizer.save(str(tokenizer_json_path))
302
+
303
+ extra_specials = [token for token in special_tokens if token not in {"<pad>", "<unk>", "<s>", "</s>"}]
304
+ fast_tokenizer = PreTrainedTokenizerFast(
305
+ tokenizer_file=str(tokenizer_json_path),
306
+ bos_token="<s>",
307
+ eos_token="</s>",
308
+ unk_token="<unk>",
309
+ pad_token="<pad>",
310
+ additional_special_tokens=extra_specials,
311
+ )
312
+ fast_tokenizer.model_max_length = max(256, as_int(data_cfg.get("max_seq_length"), 2048))
313
+ fast_tokenizer.save_pretrained(str(tokenizer_dir))
314
+
315
+ return fast_tokenizer
316
+
317
+
318
+ def tokenize_datasets(raw: DatasetDict, tokenizer: PreTrainedTokenizerFast, data_cfg: Dict[str, Any]) -> DatasetDict:
319
+ max_len = max(128, as_int(data_cfg.get("max_seq_length"), 2048))
320
+ eos = tokenizer.eos_token or ""
321
+ remove_columns = raw["train"].column_names
322
+
323
+ def _tokenize(row: Dict[str, Any]) -> Dict[str, Any]:
324
+ prompt_text = build_prompt_text(row, data_cfg)
325
+ answer_text = build_answer_block(row, data_cfg)
326
+ full_text = f"{prompt_text}{answer_text}{eos}"
327
+
328
+ prompt_ids = tokenizer(prompt_text, add_special_tokens=False)["input_ids"]
329
+ full_enc = tokenizer(
330
+ full_text,
331
+ add_special_tokens=False,
332
+ truncation=True,
333
+ max_length=max_len,
334
+ )
335
+ input_ids = full_enc["input_ids"]
336
+ attention_mask = full_enc["attention_mask"]
337
+
338
+ if not input_ids:
339
+ fallback = tokenizer.eos_token_id
340
+ if fallback is None:
341
+ fallback = tokenizer.pad_token_id
342
+ if fallback is None:
343
+ fallback = 0
344
+ return {
345
+ "input_ids": [fallback],
346
+ "attention_mask": [1],
347
+ "labels": [fallback],
348
+ }
349
+
350
+ prompt_len = min(len(prompt_ids), len(input_ids))
351
+ labels = [-100] * prompt_len + input_ids[prompt_len:]
352
+ if prompt_len >= len(input_ids):
353
+ labels[-1] = input_ids[-1]
354
+
355
+ return {
356
+ "input_ids": input_ids,
357
+ "attention_mask": attention_mask,
358
+ "labels": labels,
359
+ }
360
+
361
+ tokenized = raw.map(
362
+ _tokenize,
363
+ remove_columns=remove_columns,
364
+ desc="Tokenizing prompt/answer pairs",
365
+ )
366
+ tokenized = tokenized.filter(
367
+ lambda row: any(token != -100 for token in row["labels"]),
368
+ desc="Dropping prompt-only rows",
369
+ )
370
+ return tokenized
371
+
372
+
373
+ def build_model_from_scratch(model_cfg: Dict[str, Any], tokenizer: PreTrainedTokenizerFast, max_seq_length: int) -> GPT2LMHeadModel:
374
+ n_layer = max(2, as_int(model_cfg.get("n_layer"), 12))
375
+ n_head = max(2, as_int(model_cfg.get("n_head"), 12))
376
+ n_embd = max(128, as_int(model_cfg.get("n_embd"), 768))
377
+ if n_embd % n_head != 0:
378
+ raise ValueError("model.n_embd must be divisible by model.n_head.")
379
+
380
+ n_positions = max(max_seq_length, as_int(model_cfg.get("n_positions"), max_seq_length))
381
+
382
+ config = GPT2Config(
383
+ vocab_size=len(tokenizer),
384
+ n_positions=n_positions,
385
+ n_ctx=n_positions,
386
+ n_embd=n_embd,
387
+ n_layer=n_layer,
388
+ n_head=n_head,
389
+ resid_pdrop=as_float(model_cfg.get("resid_pdrop"), 0.1),
390
+ embd_pdrop=as_float(model_cfg.get("embd_pdrop"), 0.1),
391
+ attn_pdrop=as_float(model_cfg.get("attn_pdrop"), 0.1),
392
+ initializer_range=as_float(model_cfg.get("initializer_range"), 0.02),
393
+ bos_token_id=tokenizer.bos_token_id,
394
+ eos_token_id=tokenizer.eos_token_id,
395
+ pad_token_id=tokenizer.pad_token_id,
396
+ )
397
+
398
+ model = GPT2LMHeadModel(config)
399
+ model.config.use_cache = False
400
+ return model
401
+
402
+
403
+ def build_training_args(cfg: Dict[str, Any], has_eval_split: bool) -> TrainingArguments:
404
+ model_cfg = cfg["model"]
405
+ training_cfg = cfg["training"]
406
+
407
+ use_bf16_requested = bool(model_cfg.get("use_bf16", True))
408
+ cuda_available = torch.cuda.is_available()
409
+ bf16 = use_bf16_requested and cuda_available
410
+ fp16 = (not use_bf16_requested) and cuda_available
411
+
412
+ output_dir = Path(as_text(training_cfg.get("output_dir")))
413
+ output_dir.mkdir(parents=True, exist_ok=True)
414
+
415
+ max_steps_raw = training_cfg.get("max_steps")
416
+ max_steps = as_int(max_steps_raw, -1) if max_steps_raw is not None else -1
417
+
418
+ return TrainingArguments(
419
+ output_dir=str(output_dir),
420
+ num_train_epochs=as_float(training_cfg.get("num_train_epochs"), 1.0),
421
+ max_steps=max_steps,
422
+ per_device_train_batch_size=max(1, as_int(training_cfg.get("per_device_train_batch_size"), 1)),
423
+ per_device_eval_batch_size=max(1, as_int(training_cfg.get("per_device_eval_batch_size"), 1)),
424
+ gradient_accumulation_steps=max(1, as_int(training_cfg.get("gradient_accumulation_steps"), 1)),
425
+ learning_rate=as_float(training_cfg.get("learning_rate"), 2e-4),
426
+ weight_decay=as_float(training_cfg.get("weight_decay"), 0.0),
427
+ warmup_ratio=as_float(training_cfg.get("warmup_ratio"), 0.0),
428
+ lr_scheduler_type=as_text(training_cfg.get("lr_scheduler_type")) or "cosine",
429
+ max_grad_norm=as_float(training_cfg.get("max_grad_norm"), 1.0),
430
+ gradient_checkpointing=bool(training_cfg.get("gradient_checkpointing", True)),
431
+ logging_steps=max(1, as_int(training_cfg.get("logging_steps"), 10)),
432
+ save_steps=max(1, as_int(training_cfg.get("save_steps"), 250)),
433
+ save_total_limit=max(1, as_int(training_cfg.get("save_total_limit"), 3)),
434
+ dataloader_num_workers=max(0, as_int(training_cfg.get("dataloader_num_workers"), 0)),
435
+ seed=as_int(training_cfg.get("seed"), 17),
436
+ bf16=bf16,
437
+ fp16=fp16,
438
+ remove_unused_columns=False,
439
+ report_to="none",
440
+ evaluation_strategy="steps" if has_eval_split else "no",
441
+ eval_steps=max(1, as_int(training_cfg.get("eval_steps"), 250)) if has_eval_split else None,
442
+ )
443
+
444
+
445
+ def resolve_repo_id(cfg: Dict[str, Any], username: Optional[str]) -> Optional[str]:
446
+ repo_id = as_text(cfg.get("hub", {}).get("repo_id"))
447
+ if repo_id:
448
+ return repo_id
449
+ if not username:
450
+ return None
451
+ output_dir = Path(as_text(cfg["training"].get("output_dir")))
452
+ return f"{username}/{output_dir.name}"
453
+
454
+
455
+ def push_output_to_hub(output_dir: Path, repo_id: str, token: str, private: bool, commit_message: str) -> None:
456
+ api = HfApi(token=token)
457
+ api.create_repo(repo_id=repo_id, repo_type="model", private=private, exist_ok=True)
458
+ api.upload_folder(
459
+ repo_id=repo_id,
460
+ repo_type="model",
461
+ folder_path=str(output_dir),
462
+ commit_message=commit_message,
463
+ )
464
+
465
+
466
+ def save_json(path: Path, payload: Dict[str, Any]) -> None:
467
+ path.parent.mkdir(parents=True, exist_ok=True)
468
+ path.write_text(json.dumps(payload, ensure_ascii=True, indent=2) + "\n", encoding="utf-8")
469
+
470
+
471
+ def main() -> None:
472
+ args = parse_args()
473
+ cfg = load_config(args.config)
474
+ apply_overrides(cfg, args)
475
+
476
+ global_cfg = cfg["global"]
477
+ data_cfg = cfg["data"]
478
+ training_cfg = cfg["training"]
479
+
480
+ output_root = Path(as_text(global_cfg.get("output_root")))
481
+ if not output_root:
482
+ raise ValueError("global.output_root is required.")
483
+ output_root.mkdir(parents=True, exist_ok=True)
484
+
485
+ if not as_text(training_cfg.get("output_dir")):
486
+ training_cfg["output_dir"] = str(output_root / "checkpoints")
487
+
488
+ seed = as_int(global_cfg.get("seed"), 17)
489
+ training_cfg.setdefault("seed", seed)
490
+ set_seed(seed)
491
+
492
+ token, username = resolve_auth(cfg)
493
+ push_to_hub = bool(cfg.get("hub", {}).get("push_to_hub", False))
494
+ if args.dry_run:
495
+ push_to_hub = False
496
+ repo_id = resolve_repo_id(cfg, username)
497
+ if push_to_hub:
498
+ if token is None:
499
+ raise ValueError("Hub push requested but no token found.")
500
+ if repo_id is None:
501
+ raise ValueError("Hub push requested but repo_id is empty and username is unavailable.")
502
+
503
+ raw = load_raw_datasets(data_cfg)
504
+ raw["train"] = maybe_select(raw["train"], data_cfg.get("max_train_samples"))
505
+ raw["validation"] = maybe_select(raw["validation"], data_cfg.get("max_eval_samples"))
506
+
507
+ tokenizer = build_tokenizer(raw["train"], cfg["tokenizer"], data_cfg, output_root)
508
+
509
+ max_seq_length = max(128, as_int(data_cfg.get("max_seq_length"), 2048))
510
+ model = build_model_from_scratch(cfg["model"], tokenizer, max_seq_length)
511
+
512
+ output_dir = Path(as_text(training_cfg.get("output_dir")))
513
+ output_dir.mkdir(parents=True, exist_ok=True)
514
+
515
+ model_size = {
516
+ "total_parameters": int(sum(p.numel() for p in model.parameters())),
517
+ "trainable_parameters": int(sum(p.numel() for p in model.parameters() if p.requires_grad)),
518
+ }
519
+
520
+ if args.init_only or args.dry_run:
521
+ model.save_pretrained(str(output_dir), safe_serialization=True)
522
+ tokenizer.save_pretrained(str(output_dir))
523
+ summary = {
524
+ "mode": "dry_run" if args.dry_run else "init_only",
525
+ "output_dir": str(output_dir),
526
+ "tokenizer_dir": str((output_root / "tokenizer").resolve()),
527
+ "rows_train": len(raw["train"]),
528
+ "rows_validation": len(raw["validation"]),
529
+ "max_seq_length": max_seq_length,
530
+ "model": model_size,
531
+ "config_path": str(args.config),
532
+ }
533
+ save_json(output_root / "scratch_init_summary.json", summary)
534
+ save_json(output_dir / "resolved_training_config.json", cfg)
535
+ if push_to_hub and repo_id is not None and token is not None:
536
+ commit_message = as_text(cfg.get("hub", {}).get("commit_message")) or "Upload scratch-initialized model."
537
+ private = bool(cfg.get("hub", {}).get("private", False))
538
+ push_output_to_hub(output_dir, repo_id, token, private, commit_message)
539
+ print(f"Pushed model artifacts to https://huggingface.co/{repo_id}")
540
+ print(f"Scratch initialization complete. Output saved to: {output_dir}")
541
+ return
542
+
543
+ tokenized = tokenize_datasets(raw, tokenizer, data_cfg)
544
+ train_dataset = tokenized["train"]
545
+ eval_dataset = tokenized["validation"] if len(tokenized["validation"]) > 0 else None
546
+
547
+ training_args = build_training_args(cfg, has_eval_split=eval_dataset is not None)
548
+ data_collator = DataCollatorForSeq2Seq(
549
+ tokenizer=tokenizer,
550
+ model=model,
551
+ label_pad_token_id=-100,
552
+ pad_to_multiple_of=8,
553
+ )
554
+
555
+ trainer = Trainer(
556
+ model=model,
557
+ args=training_args,
558
+ train_dataset=train_dataset,
559
+ eval_dataset=eval_dataset,
560
+ tokenizer=tokenizer,
561
+ data_collator=data_collator,
562
+ )
563
+
564
+ train_result = trainer.train()
565
+ trainer.log_metrics("train", train_result.metrics)
566
+ trainer.save_metrics("train", train_result.metrics)
567
+ trainer.save_state()
568
+
569
+ if eval_dataset is not None:
570
+ eval_metrics = trainer.evaluate()
571
+ trainer.log_metrics("eval", eval_metrics)
572
+ trainer.save_metrics("eval", eval_metrics)
573
+
574
+ trainer.save_model(training_args.output_dir)
575
+ tokenizer.save_pretrained(training_args.output_dir)
576
+
577
+ save_json(output_dir / "resolved_training_config.json", cfg)
578
+ save_json(
579
+ output_dir / "scratch_model_summary.json",
580
+ {
581
+ "output_dir": str(output_dir),
582
+ "rows_train": len(train_dataset),
583
+ "rows_validation": len(eval_dataset) if eval_dataset is not None else 0,
584
+ "max_seq_length": max_seq_length,
585
+ "model": model_size,
586
+ "config_path": str(args.config),
587
+ },
588
+ )
589
+
590
+ if push_to_hub and repo_id is not None and token is not None:
591
+ commit_message = as_text(cfg.get("hub", {}).get("commit_message")) or "Upload scratch-trained model."
592
+ private = bool(cfg.get("hub", {}).get("private", False))
593
+ push_output_to_hub(Path(training_args.output_dir), repo_id, token, private, commit_message)
594
+ print(f"Pushed model artifacts to https://huggingface.co/{repo_id}")
595
+
596
+ print(f"Training finished. Output saved to: {training_args.output_dir}")
597
+
598
+
599
+ if __name__ == "__main__":
600
+ main()