Spaces:
Sleeping
Sleeping
Download utils/checkpoint.py from UTKojima/1stPaper_v1: direct link, hf CLI and curl.
- Browser
- Download file 15.7 kB
-
https://huggingface.co/spaces/UTKojima/1stPaper_v1/resolve/main/utils/checkpoint.py
- Command line
-
hf download hf://spaces/UTKojima/1stPaper_v1/utils/checkpoint.py
-
curl -L -o checkpoint.py https://huggingface.co/spaces/UTKojima/1stPaper_v1/resolve/main/utils/checkpoint.py
15.7 kB
| """ | |
| Checkpoint Management for Enhanced Symplectic LLM Experiment | |
| チェックポイント管理機能 | |
| Author: Kazuhiro Kojima | |
| Version: 1.0.0 | |
| """ | |
| import os | |
| import json | |
| import pickle | |
| import gzip | |
| import hashlib | |
| import logging | |
| from datetime import datetime, timedelta | |
| from typing import Dict, List, Any, Optional, Tuple | |
| from pathlib import Path | |
| import threading | |
| import time | |
| # ログ設定 | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| class CheckpointManager: | |
| """チェックポイント管理メインクラス""" | |
| def __init__(self, | |
| checkpoint_dir: str = "checkpoints", | |
| max_checkpoints: int = 10, | |
| compression: bool = True, | |
| auto_cleanup: bool = True): | |
| self.checkpoint_dir = Path(checkpoint_dir) | |
| self.max_checkpoints = max_checkpoints | |
| self.compression = compression | |
| self.auto_cleanup = auto_cleanup | |
| # ディレクトリ作成 | |
| self.checkpoint_dir.mkdir(exist_ok=True) | |
| # メタデータファイル | |
| self.metadata_file = self.checkpoint_dir / "checkpoint_metadata.json" | |
| self.metadata = self._load_metadata() | |
| # ロック機能 | |
| self._lock = threading.Lock() | |
| logger.info(f"💾 CheckpointManager initialized: {self.checkpoint_dir}") | |
| logger.info(f"🗂️ Max checkpoints: {self.max_checkpoints}, Compression: {self.compression}") | |
| # 自動クリーンアップ | |
| if self.auto_cleanup: | |
| self._cleanup_old_checkpoints() | |
| def save(self, checkpoint_id: str, data: Dict[str, Any], | |
| metadata: Optional[Dict[str, Any]] = None) -> str: | |
| """チェックポイント保存""" | |
| with self._lock: | |
| try: | |
| timestamp = datetime.now().isoformat() | |
| # ファイル名生成 | |
| filename = self._generate_filename(checkpoint_id) | |
| filepath = self.checkpoint_dir / filename | |
| # データ準備 | |
| checkpoint_data = { | |
| 'checkpoint_id': checkpoint_id, | |
| 'timestamp': timestamp, | |
| 'data': data, | |
| 'metadata': metadata or {}, | |
| 'version': '1.0.0' | |
| } | |
| # 保存実行 | |
| if self.compression: | |
| self._save_compressed(filepath, checkpoint_data) | |
| else: | |
| self._save_uncompressed(filepath, checkpoint_data) | |
| # メタデータ更新 | |
| file_size = filepath.stat().st_size | |
| data_hash = self._calculate_hash(str(data)) | |
| self.metadata[checkpoint_id] = { | |
| 'filename': filename, | |
| 'timestamp': timestamp, | |
| 'file_size': file_size, | |
| 'data_hash': data_hash, | |
| 'compression': self.compression, | |
| 'metadata': metadata or {} | |
| } | |
| self._save_metadata() | |
| logger.info(f"💾 Checkpoint saved: {checkpoint_id} ({file_size:,} bytes)") | |
| # 古いチェックポイントのクリーンアップ | |
| if self.auto_cleanup: | |
| self._cleanup_old_checkpoints() | |
| return str(filepath) | |
| except Exception as e: | |
| logger.error(f"❌ Checkpoint save failed: {e}") | |
| raise | |
| def load(self, checkpoint_id: str) -> Dict[str, Any]: | |
| """チェックポイント読み込み""" | |
| with self._lock: | |
| try: | |
| if not self.exists(checkpoint_id): | |
| raise FileNotFoundError(f"Checkpoint not found: {checkpoint_id}") | |
| metadata = self.metadata[checkpoint_id] | |
| filename = metadata['filename'] | |
| filepath = self.checkpoint_dir / filename | |
| # データ読み込み | |
| if metadata.get('compression', False): | |
| checkpoint_data = self._load_compressed(filepath) | |
| else: | |
| checkpoint_data = self._load_uncompressed(filepath) | |
| # データ整合性チェック | |
| loaded_hash = self._calculate_hash(str(checkpoint_data['data'])) | |
| expected_hash = metadata['data_hash'] | |
| if loaded_hash != expected_hash: | |
| logger.warning(f"⚠️ Data integrity warning for {checkpoint_id}") | |
| logger.info(f"📂 Checkpoint loaded: {checkpoint_id}") | |
| return checkpoint_data['data'] | |
| except Exception as e: | |
| logger.error(f"❌ Checkpoint load failed: {e}") | |
| raise | |
| def exists(self, checkpoint_id: str) -> bool: | |
| """チェックポイント存在確認""" | |
| return checkpoint_id in self.metadata | |
| def list_checkpoints(self) -> List[Dict[str, Any]]: | |
| """チェックポイント一覧取得""" | |
| checkpoints = [] | |
| for checkpoint_id, meta in self.metadata.items(): | |
| checkpoints.append({ | |
| 'checkpoint_id': checkpoint_id, | |
| 'timestamp': meta['timestamp'], | |
| 'file_size': meta['file_size'], | |
| 'age_hours': self._calculate_age_hours(meta['timestamp']) | |
| }) | |
| # 新しい順でソート | |
| checkpoints.sort(key=lambda x: x['timestamp'], reverse=True) | |
| return checkpoints | |
| def delete(self, checkpoint_id: str) -> bool: | |
| """チェックポイント削除""" | |
| with self._lock: | |
| try: | |
| if not self.exists(checkpoint_id): | |
| logger.warning(f"⚠️ Checkpoint not found for deletion: {checkpoint_id}") | |
| return False | |
| metadata = self.metadata[checkpoint_id] | |
| filename = metadata['filename'] | |
| filepath = self.checkpoint_dir / filename | |
| # ファイル削除 | |
| if filepath.exists(): | |
| filepath.unlink() | |
| # メタデータから削除 | |
| del self.metadata[checkpoint_id] | |
| self._save_metadata() | |
| logger.info(f"🗑️ Checkpoint deleted: {checkpoint_id}") | |
| return True | |
| except Exception as e: | |
| logger.error(f"❌ Checkpoint deletion failed: {e}") | |
| return False | |
| def get_info(self, checkpoint_id: str) -> Optional[Dict[str, Any]]: | |
| """チェックポイント情報取得""" | |
| if not self.exists(checkpoint_id): | |
| return None | |
| meta = self.metadata[checkpoint_id] | |
| return { | |
| 'checkpoint_id': checkpoint_id, | |
| 'timestamp': meta['timestamp'], | |
| 'file_size': meta['file_size'], | |
| 'age_hours': self._calculate_age_hours(meta['timestamp']), | |
| 'compression': meta.get('compression', False), | |
| 'metadata': meta.get('metadata', {}) | |
| } | |
| def _generate_filename(self, checkpoint_id: str) -> str: | |
| """ファイル名生成""" | |
| safe_id = "".join(c for c in checkpoint_id if c.isalnum() or c in "-_") | |
| timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') | |
| extension = '.pkl.gz' if self.compression else '.pkl' | |
| return f"checkpoint_{safe_id}_{timestamp}{extension}" | |
| def _save_compressed(self, filepath: Path, data: Dict[str, Any]): | |
| """圧縮保存""" | |
| with gzip.open(filepath, 'wb') as f: | |
| pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL) | |
| def _save_uncompressed(self, filepath: Path, data: Dict[str, Any]): | |
| """非圧縮保存""" | |
| with open(filepath, 'wb') as f: | |
| pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL) | |
| def _load_compressed(self, filepath: Path) -> Dict[str, Any]: | |
| """圧縮読み込み""" | |
| with gzip.open(filepath, 'rb') as f: | |
| return pickle.load(f) | |
| def _load_uncompressed(self, filepath: Path) -> Dict[str, Any]: | |
| """非圧縮読み込み""" | |
| with open(filepath, 'rb') as f: | |
| return pickle.load(f) | |
| def _calculate_hash(self, data_str: str) -> str: | |
| """データハッシュ計算""" | |
| return hashlib.md5(data_str.encode('utf-8')).hexdigest() | |
| def _calculate_age_hours(self, timestamp_str: str) -> float: | |
| """チェックポイント経過時間計算(時間)""" | |
| timestamp = datetime.fromisoformat(timestamp_str) | |
| age = datetime.now() - timestamp | |
| return age.total_seconds() / 3600 | |
| def _load_metadata(self) -> Dict[str, Any]: | |
| """メタデータ読み込み""" | |
| if self.metadata_file.exists(): | |
| try: | |
| with open(self.metadata_file, 'r', encoding='utf-8') as f: | |
| return json.load(f) | |
| except Exception as e: | |
| logger.warning(f"⚠️ Metadata load failed, creating new: {e}") | |
| return {} | |
| def _save_metadata(self): | |
| """メタデータ保存""" | |
| try: | |
| with open(self.metadata_file, 'w', encoding='utf-8') as f: | |
| json.dump(self.metadata, f, indent=2, ensure_ascii=False) | |
| except Exception as e: | |
| logger.error(f"❌ Metadata save failed: {e}") | |
| def _cleanup_old_checkpoints(self): | |
| """古いチェックポイントのクリーンアップ""" | |
| if len(self.metadata) <= self.max_checkpoints: | |
| return | |
| # 古い順でソート | |
| sorted_checkpoints = sorted( | |
| self.metadata.items(), | |
| key=lambda x: x[1]['timestamp'] | |
| ) | |
| # 古いものから削除 | |
| checkpoints_to_delete = sorted_checkpoints[:-self.max_checkpoints] | |
| for checkpoint_id, _ in checkpoints_to_delete: | |
| self.delete(checkpoint_id) | |
| if checkpoints_to_delete: | |
| logger.info(f"🧹 Cleaned up {len(checkpoints_to_delete)} old checkpoints") | |
| class AutoCheckpoint: | |
| """自動チェックポイント機能""" | |
| def __init__(self, | |
| manager: CheckpointManager, | |
| save_interval: int = 300, # 5分 | |
| enabled: bool = True): | |
| self.manager = manager | |
| self.save_interval = save_interval | |
| self.enabled = enabled | |
| self._data_buffer = {} | |
| self._last_save_time = time.time() | |
| self._timer = None | |
| if self.enabled: | |
| self._start_auto_save() | |
| def update_data(self, checkpoint_id: str, data: Dict[str, Any]): | |
| """データ更新""" | |
| self._data_buffer[checkpoint_id] = data | |
| # 即座保存が必要な場合 | |
| if time.time() - self._last_save_time > self.save_interval: | |
| self._save_all() | |
| def force_save(self): | |
| """強制保存""" | |
| self._save_all() | |
| def _save_all(self): | |
| """バッファされたデータをすべて保存""" | |
| if not self._data_buffer: | |
| return | |
| try: | |
| for checkpoint_id, data in self._data_buffer.items(): | |
| self.manager.save( | |
| checkpoint_id, | |
| data, | |
| metadata={'auto_saved': True, 'save_time': datetime.now().isoformat()} | |
| ) | |
| self._data_buffer.clear() | |
| self._last_save_time = time.time() | |
| logger.info("💾 Auto-checkpoint saved") | |
| except Exception as e: | |
| logger.error(f"❌ Auto-checkpoint save failed: {e}") | |
| def _start_auto_save(self): | |
| """自動保存開始""" | |
| def auto_save_worker(): | |
| while self.enabled: | |
| time.sleep(self.save_interval) | |
| if self._data_buffer: | |
| self._save_all() | |
| auto_save_thread = threading.Thread(target=auto_save_worker, daemon=True) | |
| auto_save_thread.start() | |
| logger.info(f"⏰ Auto-checkpoint started (interval: {self.save_interval}s)") | |
| def stop(self): | |
| """自動保存停止""" | |
| self.enabled = False | |
| self.force_save() # 最終保存 | |
| logger.info("⏹️ Auto-checkpoint stopped") | |
| # ユーティリティ関数 | |
| def save_checkpoint(checkpoint_id: str, data: Dict[str, Any], | |
| checkpoint_dir: str = "checkpoints") -> str: | |
| """クイックチェックポイント保存""" | |
| manager = CheckpointManager(checkpoint_dir) | |
| return manager.save(checkpoint_id, data) | |
| def load_checkpoint(checkpoint_id: str, | |
| checkpoint_dir: str = "checkpoints") -> Dict[str, Any]: | |
| """クイックチェックポイント読み込み""" | |
| manager = CheckpointManager(checkpoint_dir) | |
| return manager.load(checkpoint_id) | |
| def list_all_checkpoints(checkpoint_dir: str = "checkpoints") -> List[Dict[str, Any]]: | |
| """全チェックポイント一覧""" | |
| manager = CheckpointManager(checkpoint_dir) | |
| return manager.list_checkpoints() | |
| def cleanup_checkpoints(checkpoint_dir: str = "checkpoints", | |
| max_age_hours: int = 72) -> int: | |
| """期限切れチェックポイントクリーンアップ""" | |
| manager = CheckpointManager(checkpoint_dir) | |
| checkpoints = manager.list_checkpoints() | |
| deleted_count = 0 | |
| for checkpoint in checkpoints: | |
| if checkpoint['age_hours'] > max_age_hours: | |
| if manager.delete(checkpoint['checkpoint_id']): | |
| deleted_count += 1 | |
| logger.info(f"🧹 Cleaned up {deleted_count} expired checkpoints") | |
| return deleted_count | |
| # エクスポート | |
| __all__ = [ | |
| 'CheckpointManager', | |
| 'AutoCheckpoint', | |
| 'save_checkpoint', | |
| 'load_checkpoint', | |
| 'list_all_checkpoints', | |
| 'cleanup_checkpoints' | |
| ] | |
| if __name__ == "__main__": | |
| # テスト実行 | |
| print("💾 Checkpoint utilities test") | |
| # テストデータ | |
| test_data = { | |
| 'experiment_config': {'sample_size': 1000, 'n_trials': 30}, | |
| 'results': {'baseline': [0.8, 0.7, 0.9], 'treatment': [0.6, 0.5, 0.7]}, | |
| 'metadata': {'timestamp': datetime.now().isoformat()} | |
| } | |
| # CheckpointManager テスト | |
| manager = CheckpointManager(checkpoint_dir="test_checkpoints") | |
| # 保存テスト | |
| checkpoint_id = "test_experiment_001" | |
| saved_path = manager.save(checkpoint_id, test_data) | |
| print(f"✅ Checkpoint saved: {saved_path}") | |
| # 読み込みテスト | |
| loaded_data = manager.load(checkpoint_id) | |
| print(f"✅ Checkpoint loaded: {len(loaded_data)} keys") | |
| # 一覧テスト | |
| checkpoints = manager.list_checkpoints() | |
| print(f"✅ Found {len(checkpoints)} checkpoints") | |
| # AutoCheckpoint テスト | |
| auto_checkpoint = AutoCheckpoint(manager, save_interval=5, enabled=True) | |
| auto_checkpoint.update_data("auto_test", {'data': 'auto_test_data'}) | |
| print("✅ Auto-checkpoint configured") | |
| # クリーンアップテスト | |
| manager.delete(checkpoint_id) | |
| print("✅ Checkpoint deleted") | |
| print("✅ Checkpoint test completed") | |