1stPaper_v1 / utils /progress_monitor.py
UTKojima's picture
Create progress_monitor.py
3719df3 verified
Raw History Blame Contribute Delete
19.6 kB
"""
Progress Monitoring for Enhanced Symplectic LLM Experiment
進捗監視機能
Author: Kazuhiro Kojima
Version: 1.0.0
"""
import time
import psutil
import threading
import logging
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional, Callable
from dataclasses import dataclass, field
import json
from collections import deque
import numpy as np
# ログ設定
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class ProgressSnapshot:
"""進捗スナップショット"""
timestamp: str
current: int
total: int
stage: str
details: str
percentage: float
elapsed_time: float
estimated_remaining: float
@dataclass
class SystemMetrics:
"""システムメトリクス"""
timestamp: str
cpu_percent: float
memory_percent: float
memory_used_gb: float
disk_usage_percent: float
network_io: Dict[str, int] = field(default_factory=dict)
gpu_info: Dict[str, Any] = field(default_factory=dict)
class ProgressMonitor:
"""進捗監視メインクラス"""
def __init__(self,
update_interval: float = 1.0,
history_size: int = 1000,
auto_log: bool = True):
self.update_interval = update_interval
self.history_size = history_size
self.auto_log = auto_log
# 状態管理
self.current_progress = {
'current': 0,
'total': 100,
'stage': '待機中',
'details': '',
'start_time': time.time()
}
# 履歴管理
self.progress_history: deque = deque(maxlen=history_size)
self.callbacks: List[Callable] = []
# スレッド制御
self._monitoring = False
self._monitor_thread = None
self._lock = threading.Lock()
logger.info("📊 ProgressMonitor initialized")
def start_monitoring(self):
"""監視開始"""
if self._monitoring:
logger.warning("⚠️ Monitoring already started")
return
self._monitoring = True
self._monitor_thread = threading.Thread(target=self._monitor_loop, daemon=True)
self._monitor_thread.start()
logger.info("📊 Progress monitoring started")
def stop_monitoring(self):
"""監視停止"""
self._monitoring = False
if self._monitor_thread:
self._monitor_thread.join(timeout=5.0)
logger.info("⏹️ Progress monitoring stopped")
def update_progress(self, current: int, total: int, stage: str = "", details: str = ""):
"""進捗更新"""
with self._lock:
now = time.time()
elapsed = now - self.current_progress['start_time']
# 進捗計算
percentage = (current / total * 100) if total > 0 else 0
# 残り時間推定
if current > 0 and percentage > 0:
estimated_total_time = elapsed / (percentage / 100)
estimated_remaining = max(0, estimated_total_time - elapsed)
else:
estimated_remaining = 0
# 進捗更新
self.current_progress.update({
'current': current,
'total': total,
'stage': stage or self.current_progress['stage'],
'details': details or self.current_progress['details'],
'percentage': percentage,
'elapsed_time': elapsed,
'estimated_remaining': estimated_remaining
})
# スナップショット作成
snapshot = ProgressSnapshot(
timestamp=datetime.now().isoformat(),
current=current,
total=total,
stage=stage or self.current_progress['stage'],
details=details or self.current_progress['details'],
percentage=percentage,
elapsed_time=elapsed,
estimated_remaining=estimated_remaining
)
self.progress_history.append(snapshot)
# コールバック実行
self._execute_callbacks(snapshot)
# 自動ログ
if self.auto_log:
self._log_progress(snapshot)
def reset_progress(self, stage: str = "開始"):
"""進捗リセット"""
with self._lock:
self.current_progress = {
'current': 0,
'total': 100,
'stage': stage,
'details': '',
'start_time': time.time()
}
logger.info(f"🔄 Progress reset: {stage}")
def add_callback(self, callback: Callable[[ProgressSnapshot], None]):
"""コールバック追加"""
self.callbacks.append(callback)
logger.info(f"📞 Callback added: {callback.__name__}")
def get_current_status(self) -> Dict[str, Any]:
"""現在の状態取得"""
with self._lock:
return self.current_progress.copy()
def get_progress_history(self, last_n: Optional[int] = None) -> List[ProgressSnapshot]:
"""進捗履歴取得"""
history = list(self.progress_history)
if last_n:
return history[-last_n:]
return history
def get_progress_summary(self) -> Dict[str, Any]:
"""進捗サマリー取得"""
with self._lock:
current = self.current_progress
# 速度計算
recent_history = list(self.progress_history)[-10:]
if len(recent_history) >= 2:
time_diff = recent_history[-1].elapsed_time - recent_history[0].elapsed_time
progress_diff = recent_history[-1].current - recent_history[0].current
speed = progress_diff / max(time_diff, 1) if time_diff > 0 else 0
else:
speed = 0
return {
'current_stage': current['stage'],
'progress_percentage': current.get('percentage', 0),
'elapsed_time_formatted': self._format_time(current.get('elapsed_time', 0)),
'estimated_remaining_formatted': self._format_time(current.get('estimated_remaining', 0)),
'processing_speed': f"{speed:.2f} items/sec",
'total_snapshots': len(self.progress_history)
}
def _monitor_loop(self):
"""監視ループ"""
while self._monitoring:
try:
# システムメトリクス収集は省略(必要に応じて実装)
time.sleep(self.update_interval)
except Exception as e:
logger.error(f"❌ Monitor loop error: {e}")
time.sleep(self.update_interval)
def _execute_callbacks(self, snapshot: ProgressSnapshot):
"""コールバック実行"""
for callback in self.callbacks:
try:
callback(snapshot)
except Exception as e:
logger.error(f"❌ Callback error: {e}")
def _log_progress(self, snapshot: ProgressSnapshot):
"""進捗ログ出力"""
if snapshot.current % 10 == 0 or snapshot.percentage in [25, 50, 75, 100]:
logger.info(
f"📊 {snapshot.stage}: {snapshot.current}/{snapshot.total} "
f"({snapshot.percentage:.1f}%) - "
f"ETA: {self._format_time(snapshot.estimated_remaining)}"
)
def _format_time(self, seconds: float) -> str:
"""時間フォーマット"""
if seconds < 60:
return f"{seconds:.0f}秒"
elif seconds < 3600:
return f"{seconds/60:.1f}分"
else:
return f"{seconds/3600:.1f}時間"
class ExperimentTracker:
"""実験追跡専用クラス"""
def __init__(self, experiment_name: str):
self.experiment_name = experiment_name
self.progress_monitor = ProgressMonitor()
# 実験固有メトリクス
self.experiment_metrics = {
'api_calls_made': 0,
'api_errors': 0,
'samples_processed': 0,
'conditions_completed': 0,
'trials_completed': 0
}
self.phase_times = {}
self.current_phase = None
logger.info(f"🔬 ExperimentTracker initialized: {experiment_name}")
def start_phase(self, phase_name: str):
"""フェーズ開始"""
if self.current_phase:
self.end_phase()
self.current_phase = phase_name
self.phase_times[phase_name] = {'start': time.time(), 'end': None}
self.progress_monitor.reset_progress(phase_name)
logger.info(f"🚀 Phase started: {phase_name}")
def end_phase(self):
"""フェーズ終了"""
if self.current_phase and self.current_phase in self.phase_times:
self.phase_times[self.current_phase]['end'] = time.time()
duration = self.phase_times[self.current_phase]['end'] - self.phase_times[self.current_phase]['start']
logger.info(f"✅ Phase completed: {self.current_phase} ({duration:.1f}s)")
self.current_phase = None
def update_experiment_progress(self, **kwargs):
"""実験進捗更新"""
# メトリクス更新
for key, value in kwargs.items():
if key in self.experiment_metrics:
self.experiment_metrics[key] = value
# 進捗監視更新
if 'current' in kwargs and 'total' in kwargs:
self.progress_monitor.update_progress(
current=kwargs['current'],
total=kwargs['total'],
stage=kwargs.get('stage', self.current_phase or '実験中'),
details=kwargs.get('details', '')
)
def increment_metric(self, metric_name: str, increment: int = 1):
"""メトリクス増分"""
if metric_name in self.experiment_metrics:
self.experiment_metrics[metric_name] += increment
def get_experiment_summary(self) -> Dict[str, Any]:
"""実験サマリー取得"""
total_time = sum(
(times.get('end', time.time()) - times['start'])
for times in self.phase_times.values()
)
return {
'experiment_name': self.experiment_name,
'total_experiment_time': total_time,
'phase_durations': {
phase: (times.get('end', time.time()) - times['start'])
for phase, times in self.phase_times.items()
},
'metrics': self.experiment_metrics.copy(),
'progress_summary': self.progress_monitor.get_progress_summary()
}
class SystemResourceMonitor:
"""システムリソース監視クラス"""
def __init__(self, monitoring_interval: float = 5.0):
self.monitoring_interval = monitoring_interval
self.metrics_history: deque = deque(maxlen=100)
self._monitoring = False
self._monitor_thread = None
logger.info("🖥️ SystemResourceMonitor initialized")
def start_monitoring(self):
"""リソース監視開始"""
if self._monitoring:
return
self._monitoring = True
self._monitor_thread = threading.Thread(target=self._monitor_resources, daemon=True)
self._monitor_thread.start()
logger.info("🖥️ Resource monitoring started")
def stop_monitoring(self):
"""リソース監視停止"""
self._monitoring = False
if self._monitor_thread:
self._monitor_thread.join(timeout=10.0)
logger.info("⏹️ Resource monitoring stopped")
def get_current_metrics(self) -> SystemMetrics:
"""現在のシステムメトリクス取得"""
try:
# CPU使用率
cpu_percent = psutil.cpu_percent(interval=1)
# メモリ使用状況
memory = psutil.virtual_memory()
memory_percent = memory.percent
memory_used_gb = memory.used / (1024**3)
# ディスク使用状況
disk = psutil.disk_usage('/')
disk_usage_percent = disk.percent
# ネットワークI/O(オプション)
network_io = {}
try:
net_io = psutil.net_io_counters()
network_io = {
'bytes_sent': net_io.bytes_sent,
'bytes_recv': net_io.bytes_recv
}
except:
pass
return SystemMetrics(
timestamp=datetime.now().isoformat(),
cpu_percent=cpu_percent,
memory_percent=memory_percent,
memory_used_gb=memory_used_gb,
disk_usage_percent=disk_usage_percent,
network_io=network_io
)
except Exception as e:
logger.error(f"❌ Failed to get system metrics: {e}")
return SystemMetrics(
timestamp=datetime.now().isoformat(),
cpu_percent=0,
memory_percent=0,
memory_used_gb=0,
disk_usage_percent=0
)
def _monitor_resources(self):
"""リソース監視ループ"""
while self._monitoring:
try:
metrics = self.get_current_metrics()
self.metrics_history.append(metrics)
# 警告チェック
self._check_resource_warnings(metrics)
time.sleep(self.monitoring_interval)
except Exception as e:
logger.error(f"❌ Resource monitoring error: {e}")
time.sleep(self.monitoring_interval)
def _check_resource_warnings(self, metrics: SystemMetrics):
"""リソース警告チェック"""
# CPU使用率警告
if metrics.cpu_percent > 90:
logger.warning(f"⚠️ High CPU usage: {metrics.cpu_percent:.1f}%")
# メモリ使用率警告
if metrics.memory_percent > 85:
logger.warning(f"⚠️ High memory usage: {metrics.memory_percent:.1f}%")
# ディスク使用率警告
if metrics.disk_usage_percent > 90:
logger.warning(f"⚠️ High disk usage: {metrics.disk_usage_percent:.1f}%")
def get_resource_summary(self) -> Dict[str, Any]:
"""リソース使用状況サマリー"""
if not self.metrics_history:
return {'error': 'No metrics available'}
recent_metrics = list(self.metrics_history)[-10:] # 最新10件
cpu_values = [m.cpu_percent for m in recent_metrics]
memory_values = [m.memory_percent for m in recent_metrics]
return {
'current_cpu': recent_metrics[-1].cpu_percent,
'average_cpu': np.mean(cpu_values),
'max_cpu': np.max(cpu_values),
'current_memory': recent_metrics[-1].memory_percent,
'average_memory': np.mean(memory_values),
'max_memory': np.max(memory_values),
'current_memory_gb': recent_metrics[-1].memory_used_gb,
'disk_usage': recent_metrics[-1].disk_usage_percent,
'monitoring_duration': len(self.metrics_history) * self.monitoring_interval
}
# ユーティリティ関数
def create_progress_callback(format_string: str = "📊 {stage}: {current}/{total} ({percentage:.1f}%)") -> Callable:
"""進捗コールバック作成"""
def callback(snapshot: ProgressSnapshot):
message = format_string.format(
stage=snapshot.stage,
current=snapshot.current,
total=snapshot.total,
percentage=snapshot.percentage,
details=snapshot.details,
elapsed=snapshot.elapsed_time,
remaining=snapshot.estimated_remaining
)
print(message)
return callback
def create_experiment_tracker(experiment_name: str,
enable_resource_monitoring: bool = True) -> ExperimentTracker:
"""実験トラッカー作成"""
tracker = ExperimentTracker(experiment_name)
if enable_resource_monitoring:
resource_monitor = SystemResourceMonitor()
resource_monitor.start_monitoring()
# リソース情報をトラッカーに統合
tracker.resource_monitor = resource_monitor
return tracker
def save_progress_report(tracker: ExperimentTracker, filepath: str = None) -> str:
"""進捗レポート保存"""
if not filepath:
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
filepath = f"progress_report_{tracker.experiment_name}_{timestamp}.json"
report = {
'experiment_summary': tracker.get_experiment_summary(),
'progress_history': [
{
'timestamp': snapshot.timestamp,
'stage': snapshot.stage,
'percentage': snapshot.percentage,
'elapsed_time': snapshot.elapsed_time
}
for snapshot in tracker.progress_monitor.get_progress_history()
],
'resource_summary': tracker.resource_monitor.get_resource_summary() if hasattr(tracker, 'resource_monitor') else {},
'report_generated': datetime.now().isoformat()
}
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(report, f, indent=2, ensure_ascii=False)
logger.info(f"📋 Progress report saved: {filepath}")
return filepath
# エクスポート
__all__ = [
'ProgressMonitor',
'ExperimentTracker',
'SystemResourceMonitor',
'ProgressSnapshot',
'SystemMetrics',
'create_progress_callback',
'create_experiment_tracker',
'save_progress_report'
]
if __name__ == "__main__":
# テスト実行
print("📊 Progress monitoring test")
# ProgressMonitor テスト
monitor = ProgressMonitor()
monitor.start_monitoring()
# 進捗シミュレーション
for i in range(0, 101, 10):
monitor.update_progress(i, 100, "テスト実行", f"ステップ {i}")
time.sleep(0.1)
summary = monitor.get_progress_summary()
print(f"✅ Progress summary: {summary}")
monitor.stop_monitoring()
# ExperimentTracker テスト
tracker = ExperimentTracker("test_experiment")
tracker.start_phase("データ準備")
for i in range(5):
tracker.update_experiment_progress(current=i, total=5, stage="データ準備")
tracker.increment_metric('samples_processed')
time.sleep(0.1)
tracker.end_phase()
exp_summary = tracker.get_experiment_summary()
print(f"✅ Experiment summary: {exp_summary}")
# SystemResourceMonitor テスト
resource_monitor = SystemResourceMonitor()
current_metrics = resource_monitor.get_current_metrics()
print(f"✅ System metrics: CPU {current_metrics.cpu_percent}%, Memory {current_metrics.memory_percent}%")
print("✅ Progress monitoring test completed")