File size: 14,274 Bytes
18aca32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
#!/usr/bin/env python3
"""Autonomous Pear1.5 Training Runner

Runs continuously until 50B token target is reached:
1. Kaggle T4×2 (45 hrs/week) - primary
2. Kaggle TPU v5e-8 (20 hrs/week) - when T4 exhausted
3. Local RTX 5060 Ti (unlimited) - when cloud exhausted
4. Auto-resumes from latest checkpoint on HF
5. Doesn't quit until 50B tokens complete
"""
import os
import sys
import time
import json
import signal
import subprocess
import threading
from pathlib import Path
from datetime import datetime, timedelta
from typing import Optional, Dict, Any
import requests

# Add scripts to path
sys.path.insert(0, str(Path(__file__).parent))

from hardware import get_hardware_info, get_training_config, HardwareInfo, DeviceType


class AutonomousTrainer:
    def __init__(self, data_path: str, output_base: str, hf_token: str):
        self.data_path = Path(data_path)
        self.output_base = Path(output_base)
        self.hf_token = hf_token
        self.hf_repo = "coderofpears/pear15-stage3-checkpoints"
        self.target_tokens = 50_000_000_000
        self.parent_tokens = 1_739_227_136
        self.tokens_per_step = 16_384
        self.total_steps = (self.target_tokens - self.parent_tokens) // self.tokens_per_step
        
        # State
        self.current_step = 0
        self.current_tokens = 0
        self.running = True
        self.current_process: Optional[subprocess.Popen] = None
        self.current_platform = "unknown"
        self.start_time = time.time()
        
        # Platform configs
        self.platforms = [
            {"name": "kaggle-t4", "type": "kaggle", "gpu": "T4x2", "quota_hrs": 45, "priority": 1},
            {"name": "kaggle-tpu", "type": "kaggle", "gpu": "TPU-v5e-8", "quota_hrs": 20, "priority": 2},
            {"name": "local", "type": "local", "gpu": "RTX-5060-TI", "quota_hrs": 999999, "priority": 3},
        ]
        
        # Setup signal handlers
        signal.signal(signal.SIGINT, self._signal_handler)
        signal.signal(signal.SIGTERM, self._signal_handler)
        
        # Setup HF API
        import huggingface_hub
        self.api = huggingface_hub.HfApi(token=hf_token) if hf_token else None
        
    def _signal_handler(self, signum, frame):
        print(f"\nReceived signal {signum}, saving checkpoint and shutting down...")
        self.running = False
        if self.current_process:
            self.current_process.terminate()
            self.current_process.wait(timeout=30)
        sys.exit(0)
    
    def get_latest_checkpoint(self) -> Dict[str, Any]:
        """Get latest checkpoint info from HF bucket."""
        try:
            import huggingface_hub
            files = huggingface_hub.list_repo_files(self.hf_repo, repo_type="dataset", token=self.hf_token)
            checkpoints = []
            for f in files:
                if f.startswith("checkpoints/step_") and f.endswith("/manifest.json"):
                    step_str = f.split("/")[1].split("_")[1]
                    step = int(step_str)
                    checkpoints.append(step)
            if checkpoints:
                latest_step = max(checkpoints)
                return {"step": latest_step, "source": "hf"}
        except Exception as e:
            print(f"Could not fetch from HF: {e}")
        
        # Check local
        local_ckpts = sorted(self.output_base.glob("*/step_*/manifest.json"))
        if local_ckpts:
            latest = local_ckpts[-1]
            step = int(latest.parent.name.split("_")[1])
            return {"step": step, "source": "local"}
        
        return {"step": 0, "source": "none"}
    
    def download_checkpoint(self, step: int, output_dir: Path) -> bool:
        """Download checkpoint from HF."""
        if not self.api:
            return False
        try:
            output_dir.mkdir(parents=True, exist_ok=True)
            # Find the checkpoint directory name
            files = huggingface_hub.list_repo_files(self.hf_repo, repo_type="dataset", token=self.hf_token)
            ckpt_dir = None
            for f in files:
                if f.startswith(f"checkpoints/step_{step:012d}_") and f.endswith("/manifest.json"):
                    ckpt_dir = "/".join(f.split("/")[:-1])
                    break
            
            if not ckpt_dir:
                return False
            
            for fname in ["checkpoint.pt", "manifest.json", "READY"]:
                try:
                    path = huggingface_hub.hf_hub_download(
                        self.hf_repo, f"{ckpt_dir}/{fname}", 
                        repo_type="dataset", token=self.hf_token,
                        local_dir=str(output_dir / ckpt_dir)
                    )
                    # Move to flat structure
                    import shutil
                    target = output_dir / f"step_{step:012d}" / fname
                    target.parent.mkdir(parents=True, exist_ok=True)
                    shutil.move(path, target)
                except Exception as e:
                    print(f"Failed to download {fname}: {e}")
                    return False
            return True
        except Exception as e:
            print(f"Checkpoint download failed: {e}")
            return False
    
    def upload_checkpoints(self, platform_name: str):
        """Upload local checkpoints to HF."""
        if not self.api:
            return
        try:
            for ckpt_dir in self.output_base.glob("*/step_*"):
                if not ckpt_dir.is_dir():
                    continue
                for fname in ["checkpoint.pt", "manifest.json", "READY"]:
                    fpath = ckpt_dir / fname
                    if fpath.exists():
                        rel_path = fpath.relative_to(self.output_base)
                        self.api.upload_file(
                            path_or_fileobj=str(fpath),
                            path_in_repo=f"checkpoints/{rel_path}",
                            repo_id=self.hf_repo,
                            repo_type="dataset"
                        )
                        print(f"Uploaded {rel_path}")
        except Exception as e:
            print(f"Upload failed: {e}")
    
    def run_training(self, platform: str, resume_step: int, max_hours: float) -> bool:
        """Run training on specified platform."""
        print(f"\n{'='*60}")
        print(f"STARTING TRAINING ON {platform.upper()}")
        print(f"Resume from step: {resume_step}")
        print(f"Max hours: {max_hours}")
        print(f"{'='*60}")
        
        self.current_platform = platform
        output_dir = self.output_base / platform
        output_dir.mkdir(parents=True, exist_ok=True)
        
        # Download checkpoint if needed
        if resume_step > 0:
            local_ckpt = output_dir / f"step_{resume_step:012d}" / "checkpoint.pt"
            if not local_ckpt.exists():
                print(f"Downloading checkpoint step {resume_step}...")
                if not self.download_checkpoint(resume_step, output_dir):
                    print("Failed to download checkpoint, starting fresh")
                    resume_step = 0
        
        # Build command
        cmd = [
            sys.executable, str(Path(__file__).parent / "scripts" / "train_agnostic.py"),
            "--data-path", str(self.data_path),
            "--output-dir", str(output_dir),
            "--resume-from", str(resume_step),
        ]
        
        # Add platform-specific flags
        env = os.environ.copy()
        env["HF_TOKEN"] = self.hf_token
        env["PYTHONPATH"] = str(Path(__file__).parent)
        
        if platform.startswith("kaggle"):
            # Kaggle-specific env
            env["KAGGLE_KERNEL"] = "1"
            if "tpu" in platform:
                env["PJRT_DEVICE"] = "TPU"
                env["XLA_USE_BF16"] = "1"
        
        print(f"Running: {' '.join(cmd)}")
        print(f"Output dir: {output_dir}")
        
        # Run with timeout
        timeout_seconds = int(max_hours * 3600)
        start = time.time()
        
        try:
            self.current_process = subprocess.Popen(
                cmd, cwd=Path(__file__).parent.parent,
                env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                text=True, bufsize=1, universal_newlines=True
            )
            
            # Monitor output
            last_upload = time.time()
            for line in self.current_process.stdout:
                print(f"[{platform}] {line.rstrip()}")
                
                # Periodic upload
                if time.time() - last_upload > 300:  # Every 5 min
                    self.upload_checkpoints(platform)
                    last_upload = time.time()
                
                # Check for step progress
                if "step" in line.lower() and "tokens" in line.lower():
                    try:
                        import re
                        match = re.search(r"step[\\s:=]+(\\d+)", line, re.I)
                        if match:
                            self.current_step = int(match.group(1))
                            self.current_tokens = self.parent_tokens + self.current_step * self.tokens_per_step
                    except:
                        pass
                
                # Check timeout
                if time.time() - start > timeout_seconds:
                    print(f"Time limit ({max_hours}h) reached for {platform}")
                    break
            
            # Wait for process to finish
            self.current_process.wait(timeout=60)
            
        except subprocess.TimeoutExpired:
            print(f"Process timeout after {max_hours}h")
            if self.current_process:
                self.current_process.terminate()
                self.current_process.wait(timeout=30)
        except Exception as e:
            print(f"Training error on {platform}: {e}")
            return False
        finally:
            self.current_process = None
            # Final upload
            self.upload_checkpoints(platform)
        
        # Check progress
        latest = self.get_latest_checkpoint()
        self.current_step = latest["step"]
        self.current_tokens = self.parent_tokens + self.current_step * self.tokens_per_step
        
        print(f"\nPlatform {platform} finished. Current step: {self.current_step}, tokens: {self.current_tokens:,}")
        return True
    
    def run_autonomous(self):
        """Main autonomous loop - runs until target reached."""
        print(f"\n{'='*70}")
        print(f"AUTONOMOUS PEAR1.5 TRAINING - TARGET: {self.target_tokens:,} tokens")
        print(f"{'='*70}")
        print(f"Parent tokens: {self.parent_tokens:,}")
        print(f"Current step: 0")
        print(f"Platforms: T4×2 (45h) -> TPU v5e-8 (20h) -> Local (∞)")
        print(f"{'='*70}\n")
        
        while self.running and self.current_tokens < self.target_tokens:
            # Get latest progress
            latest = self.get_latest_checkpoint()
            self.current_step = latest["step"]
            self.current_tokens = self.parent_tokens + self.current_step * self.tokens_per_step
            
            progress = (self.current_tokens - self.parent_tokens) / (self.target_tokens - self.parent_tokens) * 100
            print(f"\n{'='*70}")
            print(f"PROGRESS: {self.current_tokens:,} / {self.target_tokens:,} tokens ({progress:.2f}%)")
            print(f"Current step: {self.current_step:,}")
            print(f"{'='*70}\n")
            
            # Try each platform in priority order
            for platform_config in sorted(self.platforms, key=lambda x: x["priority"]):
                platform = platform_config["name"]
                max_hours = platform_config["quota_hrs"]
                
                # Skip if we've already used this platform's quota this session
                # (In real implementation, track quota usage)
                
                print(f"Attempting platform: {platform} ({platform_config['gpu']})")
                
                success = self.run_training(platform, self.current_step, max_hours)
                
                # Check if target reached
                latest = self.get_latest_checkpoint()
                self.current_step = latest["step"]
                self.current_tokens = self.parent_tokens + self.current_step * self.tokens_per_step
                
                if self.current_tokens >= self.target_tokens:
                    print(f"\n🎉 TARGET REACHED! {self.current_tokens:,} tokens")
                    return True
                
                if not self.running:
                    print("Shutdown requested")
                    return False
                
                # Small delay between platforms
                time.sleep(10)
            
            # All platforms exhausted, wait for quota reset or continue local
            print("\nAll cloud platforms exhausted. Continuing on local...")
            time.sleep(60)  # Wait a minute before retrying
        
        print(f"\n{'='*70}")
        print(f"TRAINING COMPLETE: {self.current_tokens:,} tokens")
        print(f"{'='*70}")
        return True


def main():
    parser = argparse.ArgumentParser(description="Autonomous Pear1.5 Training")
    parser.add_argument("--data-path", default="/content/pear15-expanded-data",
                        help="Path to expanded dataset")
    parser.add_argument("--output-dir", default="/content/checkpoints",
                        help="Base output directory")
    parser.add_argument("--hf-token", default=None,
                        help="HF token (or set HF_TOKEN env var)")
    args = parser.parse_args()
    
    hf_token = args.hf_token or os.environ.get("HF_TOKEN")
    if not hf_token:
        # Try to read from local cache
        try:
            hf_token = Path.home().joinpath(".cache/huggingface/token").read_text().strip()
        except:
            pass
    
    if not hf_token:
        print("ERROR: No HF token provided. Set HF_TOKEN env var or --hf-token")
        sys.exit(1)
    
    trainer = AutonomousTrainer(args.data_path, args.output_dir, hf_token)
    trainer.run_autonomous()


if __name__ == "__main__":
    main()