File size: 11,674 Bytes
a7ae6b9 |
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 |
#!/usr/bin/env python3
"""
Elizabeth Training Manager
Advanced training management with multiple training modes and robust monitoring
"""
import os
import sys
import time
import subprocess
import signal
import logging
import json
from datetime import datetime
from pathlib import Path
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('/workspace/elizabeth_logs/training_manager.log'),
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
class TrainingManager:
"""Advanced training management for Elizabeth"""
def __init__(self):
self.script_path = "/workspace/elizabeth-repo/src/elizabeth_main.py"
self.max_restarts = 20
self.restart_delay = 30
self.process = None
self.restart_count = 0
self.training_mode = "interactive" # interactive, autonomous, learning, conversation
# Training configurations
self.training_configs = {
"interactive": {
"args": ["--interactive", "--version", "v0.0.2"],
"description": "Interactive session with human guidance"
},
"autonomous": {
"args": ["--interactive", "--version", "v0.0.2"],
"description": "Fully autonomous learning mode"
},
"learning": {
"args": ["--version", "v0.0.2"],
"input_file": "/workspace/training_data/learning_prompts.txt",
"description": "Focused learning from training data"
}
}
# Ensure directories exist
os.makedirs("/workspace/elizabeth_logs", exist_ok=True)
os.makedirs("/workspace/training_data", exist_ok=True)
# Set environment
self.set_environment()
def set_environment(self):
"""Set training environment variables"""
os.environ["HF_TOKEN"] = os.getenv("HF_TOKEN", "")
os.environ["HUGGINGFACE_HUB_ENABLE_HF_TRANSFER"] = "1"
os.environ["PYTHONUNBUFFERED"] = "1"
def start_training(self, mode="interactive"):
"""Start training session with specified mode"""
try:
config = self.training_configs.get(mode, self.training_configs["interactive"])
logger.info(f"Starting {mode} training session...")
logger.info(f"Description: {config['description']}")
# Build command
cmd = [sys.executable, self.script_path] + config["args"]
# Handle input file if specified
stdin = None
if "input_file" in config and os.path.exists(config["input_file"]):
stdin = open(config["input_file"], "r")
self.process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
universal_newlines=True,
stdin=stdin
)
logger.info(f"Training process started with PID: {self.process.pid}")
logger.info(f"Command: {' '.join(cmd)}")
return True
except Exception as e:
logger.error(f"Failed to start {mode} training: {e}")
return False
def monitor_training(self, timeout=3600):
"""Monitor training process with timeout"""
start_time = time.time()
try:
while True:
# Check timeout
if time.time() - start_time > timeout:
logger.warning(f"Training timeout after {timeout} seconds")
return "timeout"
# Check process status
return_code = self.process.poll()
if return_code is not None:
logger.info(f"Training process completed with code: {return_code}")
return "completed"
# Read output
if self.process.stdout:
output = self.process.stdout.readline()
if output:
logger.info(f"TRAINING_OUT: {output.strip()}")
if self.process.stderr:
error = self.process.stderr.readline()
if error:
logger.error(f"TRAINING_ERR: {error.strip()}")
# Check for stalls (no output for 5 minutes)
if time.time() - start_time > 300:
# Check if process is still responsive
try:
os.kill(self.process.pid, 0) # Check if process exists
except OSError:
logger.warning("Process appears to be unresponsive")
return "stalled"
time.sleep(1)
except Exception as e:
logger.error(f"Monitoring error: {e}")
return "error"
def graceful_shutdown(self):
"""Gracefully shutdown training"""
if self.process:
try:
logger.info("Initiating graceful shutdown...")
# Try gentle termination first
self.process.terminate()
# Wait for clean shutdown
for i in range(10):
if self.process.poll() is not None:
break
time.sleep(1)
# Force kill if necessary
if self.process.poll() is None:
logger.warning("Process not terminating, forcing kill...")
self.process.kill()
logger.info("Training shutdown complete")
except Exception as e:
logger.error(f"Shutdown error: {e}")
def run_continuous_training(self):
"""Main continuous training loop"""
logger.info("🚀 Starting Elizabeth Continuous Training Manager")
logger.info(f"Mode: {self.training_mode}")
logger.info(f"Max restarts: {self.max_restarts}")
training_sessions = []
while self.restart_count <= self.max_restarts:
session_start = datetime.now()
try:
# Start training session
if not self.start_training(self.training_mode):
logger.error("Failed to start training session")
break
# Monitor session
result = self.monitor_training()
session_end = datetime.now()
duration = (session_end - session_start).total_seconds()
# Record session
session_info = {
"start": session_start.isoformat(),
"end": session_end.isoformat(),
"duration": duration,
"result": result,
"restart_count": self.restart_count,
"pid": self.process.pid if self.process else None
}
training_sessions.append(session_info)
logger.info(f"Session completed: {result}, Duration: {duration:.1f}s")
# Handle session result
if result == "completed":
logger.info("Training session completed successfully")
break
elif self.restart_count < self.max_restarts:
self.restart_count += 1
logger.warning(f"Restarting training ({self.restart_count}/{self.max_restarts})...")
logger.info(f"Waiting {self.restart_delay} seconds before restart...")
# Save session history
self.save_session_history(training_sessions)
time.sleep(self.restart_delay)
else:
logger.error("Max restart attempts reached")
break
except KeyboardInterrupt:
logger.info("Received interrupt signal")
break
except Exception as e:
logger.error(f"Unexpected error: {e}")
self.restart_count += 1
if self.restart_count <= self.max_restarts:
logger.info(f"Restarting after error... ({self.restart_count}/{self.max_restarts})")
time.sleep(self.restart_delay)
else:
break
# Final cleanup and reporting
self.graceful_shutdown()
self.save_session_history(training_sessions)
logger.info("Training manager shutting down")
logger.info(f"Total sessions: {len(training_sessions)}")
logger.info(f"Total restarts: {self.restart_count}")
def save_session_history(self, sessions):
"""Save training session history"""
try:
history_file = "/workspace/elizabeth_logs/training_history.json"
with open(history_file, 'w') as f:
json.dump({
"sessions": sessions,
"total_sessions": len(sessions),
"total_restarts": self.restart_count,
"last_update": datetime.now().isoformat()
}, f, indent=2)
except Exception as e:
logger.error(f"Failed to save session history: {e}")
def get_status(self):
"""Get current status"""
return {
"training_mode": self.training_mode,
"restart_count": self.restart_count,
"max_restarts": self.max_restarts,
"process_active": self.process and self.process.poll() is None,
"process_pid": self.process.pid if self.process else None,
"timestamp": datetime.now().isoformat()
}
def main():
"""Command line interface"""
import argparse
parser = argparse.ArgumentParser(description="Elizabeth Training Manager")
parser.add_argument("--start", action="store_true", help="Start continuous training")
parser.add_argument("--mode", choices=['interactive', 'autonomous', 'learning'],
default='interactive', help="Training mode")
parser.add_argument("--status", action="store_true", help="Show status")
parser.add_argument("--stop", action="store_true", help="Stop training")
parser.add_argument("--max-restarts", type=int, default=20, help="Max restart attempts")
parser.add_argument("--restart-delay", type=int, default=30, help="Restart delay in seconds")
args = parser.parse_args()
manager = TrainingManager()
manager.max_restarts = args.max_restarts
manager.restart_delay = args.restart_delay
manager.training_mode = args.mode
if args.start:
manager.run_continuous_training()
elif args.status:
status = manager.get_status()
print("Training Manager Status:")
for key, value in status.items():
print(f" {key}: {value}")
elif args.stop:
manager.graceful_shutdown()
print("Shutdown signal sent")
else:
print("No action specified. Use --help for options.")
if __name__ == "__main__":
main() |