coderofpears commited on
Commit
18aca32
·
verified ·
1 Parent(s): f6c0476

Upload scripts/autonomous_trainer.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/autonomous_trainer.py +348 -0
scripts/autonomous_trainer.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Autonomous Pear1.5 Training Runner
3
+
4
+ Runs continuously until 50B token target is reached:
5
+ 1. Kaggle T4×2 (45 hrs/week) - primary
6
+ 2. Kaggle TPU v5e-8 (20 hrs/week) - when T4 exhausted
7
+ 3. Local RTX 5060 Ti (unlimited) - when cloud exhausted
8
+ 4. Auto-resumes from latest checkpoint on HF
9
+ 5. Doesn't quit until 50B tokens complete
10
+ """
11
+ import os
12
+ import sys
13
+ import time
14
+ import json
15
+ import signal
16
+ import subprocess
17
+ import threading
18
+ from pathlib import Path
19
+ from datetime import datetime, timedelta
20
+ from typing import Optional, Dict, Any
21
+ import requests
22
+
23
+ # Add scripts to path
24
+ sys.path.insert(0, str(Path(__file__).parent))
25
+
26
+ from hardware import get_hardware_info, get_training_config, HardwareInfo, DeviceType
27
+
28
+
29
+ class AutonomousTrainer:
30
+ def __init__(self, data_path: str, output_base: str, hf_token: str):
31
+ self.data_path = Path(data_path)
32
+ self.output_base = Path(output_base)
33
+ self.hf_token = hf_token
34
+ self.hf_repo = "coderofpears/pear15-stage3-checkpoints"
35
+ self.target_tokens = 50_000_000_000
36
+ self.parent_tokens = 1_739_227_136
37
+ self.tokens_per_step = 16_384
38
+ self.total_steps = (self.target_tokens - self.parent_tokens) // self.tokens_per_step
39
+
40
+ # State
41
+ self.current_step = 0
42
+ self.current_tokens = 0
43
+ self.running = True
44
+ self.current_process: Optional[subprocess.Popen] = None
45
+ self.current_platform = "unknown"
46
+ self.start_time = time.time()
47
+
48
+ # Platform configs
49
+ self.platforms = [
50
+ {"name": "kaggle-t4", "type": "kaggle", "gpu": "T4x2", "quota_hrs": 45, "priority": 1},
51
+ {"name": "kaggle-tpu", "type": "kaggle", "gpu": "TPU-v5e-8", "quota_hrs": 20, "priority": 2},
52
+ {"name": "local", "type": "local", "gpu": "RTX-5060-TI", "quota_hrs": 999999, "priority": 3},
53
+ ]
54
+
55
+ # Setup signal handlers
56
+ signal.signal(signal.SIGINT, self._signal_handler)
57
+ signal.signal(signal.SIGTERM, self._signal_handler)
58
+
59
+ # Setup HF API
60
+ import huggingface_hub
61
+ self.api = huggingface_hub.HfApi(token=hf_token) if hf_token else None
62
+
63
+ def _signal_handler(self, signum, frame):
64
+ print(f"\nReceived signal {signum}, saving checkpoint and shutting down...")
65
+ self.running = False
66
+ if self.current_process:
67
+ self.current_process.terminate()
68
+ self.current_process.wait(timeout=30)
69
+ sys.exit(0)
70
+
71
+ def get_latest_checkpoint(self) -> Dict[str, Any]:
72
+ """Get latest checkpoint info from HF bucket."""
73
+ try:
74
+ import huggingface_hub
75
+ files = huggingface_hub.list_repo_files(self.hf_repo, repo_type="dataset", token=self.hf_token)
76
+ checkpoints = []
77
+ for f in files:
78
+ if f.startswith("checkpoints/step_") and f.endswith("/manifest.json"):
79
+ step_str = f.split("/")[1].split("_")[1]
80
+ step = int(step_str)
81
+ checkpoints.append(step)
82
+ if checkpoints:
83
+ latest_step = max(checkpoints)
84
+ return {"step": latest_step, "source": "hf"}
85
+ except Exception as e:
86
+ print(f"Could not fetch from HF: {e}")
87
+
88
+ # Check local
89
+ local_ckpts = sorted(self.output_base.glob("*/step_*/manifest.json"))
90
+ if local_ckpts:
91
+ latest = local_ckpts[-1]
92
+ step = int(latest.parent.name.split("_")[1])
93
+ return {"step": step, "source": "local"}
94
+
95
+ return {"step": 0, "source": "none"}
96
+
97
+ def download_checkpoint(self, step: int, output_dir: Path) -> bool:
98
+ """Download checkpoint from HF."""
99
+ if not self.api:
100
+ return False
101
+ try:
102
+ output_dir.mkdir(parents=True, exist_ok=True)
103
+ # Find the checkpoint directory name
104
+ files = huggingface_hub.list_repo_files(self.hf_repo, repo_type="dataset", token=self.hf_token)
105
+ ckpt_dir = None
106
+ for f in files:
107
+ if f.startswith(f"checkpoints/step_{step:012d}_") and f.endswith("/manifest.json"):
108
+ ckpt_dir = "/".join(f.split("/")[:-1])
109
+ break
110
+
111
+ if not ckpt_dir:
112
+ return False
113
+
114
+ for fname in ["checkpoint.pt", "manifest.json", "READY"]:
115
+ try:
116
+ path = huggingface_hub.hf_hub_download(
117
+ self.hf_repo, f"{ckpt_dir}/{fname}",
118
+ repo_type="dataset", token=self.hf_token,
119
+ local_dir=str(output_dir / ckpt_dir)
120
+ )
121
+ # Move to flat structure
122
+ import shutil
123
+ target = output_dir / f"step_{step:012d}" / fname
124
+ target.parent.mkdir(parents=True, exist_ok=True)
125
+ shutil.move(path, target)
126
+ except Exception as e:
127
+ print(f"Failed to download {fname}: {e}")
128
+ return False
129
+ return True
130
+ except Exception as e:
131
+ print(f"Checkpoint download failed: {e}")
132
+ return False
133
+
134
+ def upload_checkpoints(self, platform_name: str):
135
+ """Upload local checkpoints to HF."""
136
+ if not self.api:
137
+ return
138
+ try:
139
+ for ckpt_dir in self.output_base.glob("*/step_*"):
140
+ if not ckpt_dir.is_dir():
141
+ continue
142
+ for fname in ["checkpoint.pt", "manifest.json", "READY"]:
143
+ fpath = ckpt_dir / fname
144
+ if fpath.exists():
145
+ rel_path = fpath.relative_to(self.output_base)
146
+ self.api.upload_file(
147
+ path_or_fileobj=str(fpath),
148
+ path_in_repo=f"checkpoints/{rel_path}",
149
+ repo_id=self.hf_repo,
150
+ repo_type="dataset"
151
+ )
152
+ print(f"Uploaded {rel_path}")
153
+ except Exception as e:
154
+ print(f"Upload failed: {e}")
155
+
156
+ def run_training(self, platform: str, resume_step: int, max_hours: float) -> bool:
157
+ """Run training on specified platform."""
158
+ print(f"\n{'='*60}")
159
+ print(f"STARTING TRAINING ON {platform.upper()}")
160
+ print(f"Resume from step: {resume_step}")
161
+ print(f"Max hours: {max_hours}")
162
+ print(f"{'='*60}")
163
+
164
+ self.current_platform = platform
165
+ output_dir = self.output_base / platform
166
+ output_dir.mkdir(parents=True, exist_ok=True)
167
+
168
+ # Download checkpoint if needed
169
+ if resume_step > 0:
170
+ local_ckpt = output_dir / f"step_{resume_step:012d}" / "checkpoint.pt"
171
+ if not local_ckpt.exists():
172
+ print(f"Downloading checkpoint step {resume_step}...")
173
+ if not self.download_checkpoint(resume_step, output_dir):
174
+ print("Failed to download checkpoint, starting fresh")
175
+ resume_step = 0
176
+
177
+ # Build command
178
+ cmd = [
179
+ sys.executable, str(Path(__file__).parent / "scripts" / "train_agnostic.py"),
180
+ "--data-path", str(self.data_path),
181
+ "--output-dir", str(output_dir),
182
+ "--resume-from", str(resume_step),
183
+ ]
184
+
185
+ # Add platform-specific flags
186
+ env = os.environ.copy()
187
+ env["HF_TOKEN"] = self.hf_token
188
+ env["PYTHONPATH"] = str(Path(__file__).parent)
189
+
190
+ if platform.startswith("kaggle"):
191
+ # Kaggle-specific env
192
+ env["KAGGLE_KERNEL"] = "1"
193
+ if "tpu" in platform:
194
+ env["PJRT_DEVICE"] = "TPU"
195
+ env["XLA_USE_BF16"] = "1"
196
+
197
+ print(f"Running: {' '.join(cmd)}")
198
+ print(f"Output dir: {output_dir}")
199
+
200
+ # Run with timeout
201
+ timeout_seconds = int(max_hours * 3600)
202
+ start = time.time()
203
+
204
+ try:
205
+ self.current_process = subprocess.Popen(
206
+ cmd, cwd=Path(__file__).parent.parent,
207
+ env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
208
+ text=True, bufsize=1, universal_newlines=True
209
+ )
210
+
211
+ # Monitor output
212
+ last_upload = time.time()
213
+ for line in self.current_process.stdout:
214
+ print(f"[{platform}] {line.rstrip()}")
215
+
216
+ # Periodic upload
217
+ if time.time() - last_upload > 300: # Every 5 min
218
+ self.upload_checkpoints(platform)
219
+ last_upload = time.time()
220
+
221
+ # Check for step progress
222
+ if "step" in line.lower() and "tokens" in line.lower():
223
+ try:
224
+ import re
225
+ match = re.search(r"step[\\s:=]+(\\d+)", line, re.I)
226
+ if match:
227
+ self.current_step = int(match.group(1))
228
+ self.current_tokens = self.parent_tokens + self.current_step * self.tokens_per_step
229
+ except:
230
+ pass
231
+
232
+ # Check timeout
233
+ if time.time() - start > timeout_seconds:
234
+ print(f"Time limit ({max_hours}h) reached for {platform}")
235
+ break
236
+
237
+ # Wait for process to finish
238
+ self.current_process.wait(timeout=60)
239
+
240
+ except subprocess.TimeoutExpired:
241
+ print(f"Process timeout after {max_hours}h")
242
+ if self.current_process:
243
+ self.current_process.terminate()
244
+ self.current_process.wait(timeout=30)
245
+ except Exception as e:
246
+ print(f"Training error on {platform}: {e}")
247
+ return False
248
+ finally:
249
+ self.current_process = None
250
+ # Final upload
251
+ self.upload_checkpoints(platform)
252
+
253
+ # Check progress
254
+ latest = self.get_latest_checkpoint()
255
+ self.current_step = latest["step"]
256
+ self.current_tokens = self.parent_tokens + self.current_step * self.tokens_per_step
257
+
258
+ print(f"\nPlatform {platform} finished. Current step: {self.current_step}, tokens: {self.current_tokens:,}")
259
+ return True
260
+
261
+ def run_autonomous(self):
262
+ """Main autonomous loop - runs until target reached."""
263
+ print(f"\n{'='*70}")
264
+ print(f"AUTONOMOUS PEAR1.5 TRAINING - TARGET: {self.target_tokens:,} tokens")
265
+ print(f"{'='*70}")
266
+ print(f"Parent tokens: {self.parent_tokens:,}")
267
+ print(f"Current step: 0")
268
+ print(f"Platforms: T4×2 (45h) -> TPU v5e-8 (20h) -> Local (∞)")
269
+ print(f"{'='*70}\n")
270
+
271
+ while self.running and self.current_tokens < self.target_tokens:
272
+ # Get latest progress
273
+ latest = self.get_latest_checkpoint()
274
+ self.current_step = latest["step"]
275
+ self.current_tokens = self.parent_tokens + self.current_step * self.tokens_per_step
276
+
277
+ progress = (self.current_tokens - self.parent_tokens) / (self.target_tokens - self.parent_tokens) * 100
278
+ print(f"\n{'='*70}")
279
+ print(f"PROGRESS: {self.current_tokens:,} / {self.target_tokens:,} tokens ({progress:.2f}%)")
280
+ print(f"Current step: {self.current_step:,}")
281
+ print(f"{'='*70}\n")
282
+
283
+ # Try each platform in priority order
284
+ for platform_config in sorted(self.platforms, key=lambda x: x["priority"]):
285
+ platform = platform_config["name"]
286
+ max_hours = platform_config["quota_hrs"]
287
+
288
+ # Skip if we've already used this platform's quota this session
289
+ # (In real implementation, track quota usage)
290
+
291
+ print(f"Attempting platform: {platform} ({platform_config['gpu']})")
292
+
293
+ success = self.run_training(platform, self.current_step, max_hours)
294
+
295
+ # Check if target reached
296
+ latest = self.get_latest_checkpoint()
297
+ self.current_step = latest["step"]
298
+ self.current_tokens = self.parent_tokens + self.current_step * self.tokens_per_step
299
+
300
+ if self.current_tokens >= self.target_tokens:
301
+ print(f"\n🎉 TARGET REACHED! {self.current_tokens:,} tokens")
302
+ return True
303
+
304
+ if not self.running:
305
+ print("Shutdown requested")
306
+ return False
307
+
308
+ # Small delay between platforms
309
+ time.sleep(10)
310
+
311
+ # All platforms exhausted, wait for quota reset or continue local
312
+ print("\nAll cloud platforms exhausted. Continuing on local...")
313
+ time.sleep(60) # Wait a minute before retrying
314
+
315
+ print(f"\n{'='*70}")
316
+ print(f"TRAINING COMPLETE: {self.current_tokens:,} tokens")
317
+ print(f"{'='*70}")
318
+ return True
319
+
320
+
321
+ def main():
322
+ parser = argparse.ArgumentParser(description="Autonomous Pear1.5 Training")
323
+ parser.add_argument("--data-path", default="/content/pear15-expanded-data",
324
+ help="Path to expanded dataset")
325
+ parser.add_argument("--output-dir", default="/content/checkpoints",
326
+ help="Base output directory")
327
+ parser.add_argument("--hf-token", default=None,
328
+ help="HF token (or set HF_TOKEN env var)")
329
+ args = parser.parse_args()
330
+
331
+ hf_token = args.hf_token or os.environ.get("HF_TOKEN")
332
+ if not hf_token:
333
+ # Try to read from local cache
334
+ try:
335
+ hf_token = Path.home().joinpath(".cache/huggingface/token").read_text().strip()
336
+ except:
337
+ pass
338
+
339
+ if not hf_token:
340
+ print("ERROR: No HF token provided. Set HF_TOKEN env var or --hf-token")
341
+ sys.exit(1)
342
+
343
+ trainer = AutonomousTrainer(args.data_path, args.output_dir, hf_token)
344
+ trainer.run_autonomous()
345
+
346
+
347
+ if __name__ == "__main__":
348
+ main()