Download scripts/autonomous_trainer.py from coderofpears/pear15-stage3-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 14.3 kB
-
https://huggingface.co/datasets/coderofpears/pear15-stage3-checkpoints/resolve/main/scripts/autonomous_trainer.py
- Command line
-
hf download hf://datasets/coderofpears/pear15-stage3-checkpoints/scripts/autonomous_trainer.py
-
curl -L -o autonomous_trainer.py https://huggingface.co/datasets/coderofpears/pear15-stage3-checkpoints/resolve/main/scripts/autonomous_trainer.py
14.3 kB
| #!/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() |