Spaces:
Running on Zero
Running on Zero
Download evolution/model_registry.py from Lunaron/lunaron-audio-separation: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/spaces/Lunaron/lunaron-audio-separation/resolve/main/evolution/model_registry.py
- Command line
-
hf download hf://spaces/Lunaron/lunaron-audio-separation/evolution/model_registry.py
-
curl -L -o model_registry.py https://huggingface.co/spaces/Lunaron/lunaron-audio-separation/resolve/main/evolution/model_registry.py
14.6 kB
| """ | |
| Lunaron Evolution Engine - Model Registry | |
| Governs Model States: Champion, Challenger, Archived, Rejected. | |
| Strict Safety Rule: Production model files are NEVER overwritten directly. | |
| Promotion requires explicit administrator approval. | |
| """ | |
| import os | |
| import json | |
| import time | |
| import shutil | |
| import hashlib | |
| import re | |
| import tempfile | |
| from contextlib import contextmanager | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Dict, List, Optional, Any | |
| class RegistryError(RuntimeError): | |
| """内部Pathや元例外を外部応答へ出さない、固定のエラー契約。""" | |
| MESSAGES = { | |
| "TRAINING_INGESTION_NOT_READY": "許諾済みAssetと実測評価の確認前は、通常Uploadの学習取込を開始しません。", | |
| "BATCH_RECOVERY_NOT_READY": "単一Assetの復旧と検証が完了するまで、自動バッチ学習を開始しません。", | |
| "MODEL_REGISTRY_UNAVAILABLE": "モデル登録情報を安全に読み書きできません。", | |
| "MODEL_REGISTRY_CONFLICT": "モデル登録処理が競合しました。状態を再確認してください。", | |
| "MODEL_ID_ALREADY_EXISTS": "同じ候補IDが登録済みです。既存Checkpointは変更していません。", | |
| "MODEL_ID_INVALID": "モデル登録の識別子または状態が正しくありません。", | |
| "CHECKPOINT_NOT_FOUND": "候補Checkpointを確認できません。", | |
| "CHECKPOINT_WRITE_FAILED": "候補Checkpointの保存が完了していません。", | |
| "MODEL_METRICS_INVALID": "モデルの評価値が有効な数値ではありません。", | |
| "RECOVERY_GATE_REQUIRED": "単一Asset復旧と評価・承認を確認するまで本番昇格を停止しています。", | |
| } | |
| def __init__(self, code, stage): | |
| self.code = code | |
| self.stage = stage | |
| self.message = self.MESSAGES[code] | |
| super().__init__(self.message) | |
| def as_error(self): | |
| return {"code": self.code, "stage": self.stage, "message": self.message} | |
| class ModelRegistry: | |
| """ | |
| Production-Safe Model Registry & Lifecycle Manager. | |
| Manages promotion, rollback, and metadata for Refiner and Critic candidates. | |
| """ | |
| def __init__(self, base_dir: str = "models", *, read_only: bool = False): | |
| self.base_dir = Path(base_dir) | |
| self.champion_dir = self.base_dir / "champion" | |
| self.challenger_dir = self.base_dir / "challenger" | |
| self.archive_dir = self.base_dir / "archive" | |
| self.registry_file = self.base_dir / "registry.json" | |
| self.read_only = read_only | |
| if read_only: | |
| # 欠損を空のRegistryで補わず、状態確認では何も作らない。 | |
| try: | |
| absolute = self.base_dir.absolute() | |
| if any(part.is_symlink() for part in (absolute, *absolute.parents)) or self.registry_file.is_symlink(): | |
| raise RegistryError("MODEL_REGISTRY_UNAVAILABLE", "read_only_status") | |
| self._read_data() | |
| except OSError as error: | |
| raise RegistryError("MODEL_REGISTRY_UNAVAILABLE", "read_only_status") from error | |
| return | |
| self.champion_dir.mkdir(parents=True, exist_ok=True) | |
| self.challenger_dir.mkdir(parents=True, exist_ok=True) | |
| self.archive_dir.mkdir(parents=True, exist_ok=True) | |
| self._load_or_init_registry() | |
| def _load_or_init_registry(self): | |
| # 同時の初回読取でも既存Registryをtruncateしない。 | |
| if self.read_only: | |
| raise RegistryError("MODEL_REGISTRY_UNAVAILABLE", "read_only_status") | |
| if self.registry_file.exists(): | |
| self._read_data() | |
| return | |
| initial = {"models": {}, "active_champion": {"refiner": None, "critic": None}} | |
| try: | |
| with self.registry_file.open("x", encoding="utf-8") as handle: | |
| json.dump(initial, handle, indent=2, ensure_ascii=False, allow_nan=False) | |
| handle.flush() | |
| os.fsync(handle.fileno()) | |
| except FileExistsError: | |
| pass | |
| except OSError as error: | |
| raise RegistryError("MODEL_REGISTRY_UNAVAILABLE", "model_registry") from error | |
| self._read_data() | |
| def _read_data(self) -> Dict[str, Any]: | |
| def reject_duplicate_keys(pairs): | |
| data = {} | |
| for key, value in pairs: | |
| if key in data: | |
| raise ValueError("duplicate_key") | |
| data[key] = value | |
| return data | |
| def reject_constant(value): | |
| raise ValueError("non_finite_json") | |
| try: | |
| with self.registry_file.open("r", encoding="utf-8") as handle: | |
| data = json.load(handle, object_pairs_hook=reject_duplicate_keys, | |
| parse_constant=reject_constant) | |
| if not isinstance(data, dict) or not isinstance(data.get("models"), dict) or not isinstance(data.get("active_champion"), dict): | |
| raise ValueError("invalid_registry") | |
| for model_id, record in data["models"].items(): | |
| if not isinstance(record, dict) or record.get("model_id") != model_id or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", model_id): | |
| raise ValueError("invalid_model_record") | |
| if record.get("state") not in ("champion", "challenger", "archived", "rejected") or not isinstance(record.get("model_type"), str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", record["model_type"]) or not isinstance(record.get("weights_path"), str) or not record["weights_path"]: | |
| raise ValueError("invalid_model_metadata") | |
| for model_type, model_id in data["active_champion"].items(): | |
| if model_id is None: | |
| continue | |
| record = data["models"].get(model_id) if isinstance(model_id, str) else None | |
| if not record or record.get("state") != "champion" or record.get("model_type") != model_type: | |
| raise ValueError("invalid_champion_reference") | |
| return data | |
| except (OSError, ValueError, TypeError) as error: | |
| raise RegistryError("MODEL_REGISTRY_UNAVAILABLE", "model_registry") from error | |
| def _write_data(self, data: Dict[str, Any]): | |
| # 途中書込を本体へ公開しない。既存Registryをエラー時に空で置換しない。 | |
| if self.read_only: | |
| raise RegistryError("MODEL_REGISTRY_UNAVAILABLE", "read_only_status") | |
| temporary = None | |
| try: | |
| payload = json.dumps(data, indent=2, ensure_ascii=False, allow_nan=False) | |
| with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=self.base_dir, | |
| prefix=".registry-", suffix=".tmp", delete=False) as handle: | |
| temporary = Path(handle.name) | |
| handle.write(payload) | |
| handle.flush() | |
| os.fsync(handle.fileno()) | |
| os.replace(temporary, self.registry_file) | |
| temporary = None | |
| except (OSError, ValueError, TypeError) as error: | |
| raise RegistryError("MODEL_REGISTRY_UNAVAILABLE", "model_registry") from error | |
| finally: | |
| if temporary is not None and temporary.parent.resolve() == self.base_dir.resolve(): | |
| try: | |
| temporary.unlink() | |
| except OSError: | |
| pass | |
| def _registration_lock(self): | |
| if self.read_only: | |
| raise RegistryError("MODEL_REGISTRY_UNAVAILABLE", "read_only_status") | |
| lock = self.base_dir / ".registry-write.lock" | |
| handle = None | |
| try: | |
| handle = lock.open("x", encoding="utf-8") | |
| except FileExistsError as error: | |
| # stale lockを自動削除して重複Writerを許可しない。 | |
| raise RegistryError("MODEL_REGISTRY_CONFLICT", "model_registry") from error | |
| except OSError as error: | |
| raise RegistryError("MODEL_REGISTRY_UNAVAILABLE", "model_registry") from error | |
| try: | |
| yield | |
| finally: | |
| handle.close() | |
| try: | |
| lock.unlink() | |
| except OSError: | |
| pass | |
| def register_model( | |
| self, model_id: str, model_type: str, state: str, weights_path: str, | |
| metrics: Optional[Dict[str, Any]] = None, | |
| config: Optional[Dict[str, Any]] = None, notes: str = "" | |
| ) -> Dict[str, Any]: | |
| # 過去の未検証PASSや自己申告metricsを昇格許可として採用しない。 | |
| if self.read_only: | |
| raise RegistryError("MODEL_REGISTRY_UNAVAILABLE", "read_only_status") | |
| if state == "champion": | |
| raise RegistryError("RECOVERY_GATE_REQUIRED", "promotion_gate") | |
| if not isinstance(model_id, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", model_id) or not isinstance(model_type, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", model_type) or state not in ("challenger", "archived", "rejected"): | |
| raise RegistryError("MODEL_ID_INVALID", "candidate_registration") | |
| if (metrics is not None and not isinstance(metrics, dict)) or (config is not None and not isinstance(config, dict)) or not isinstance(notes, str): | |
| raise RegistryError("MODEL_METRICS_INVALID", "candidate_registration") | |
| try: | |
| json.dumps({"metrics": metrics, "config": config}, allow_nan=False) | |
| except (ValueError, TypeError): | |
| raise RegistryError("MODEL_METRICS_INVALID", "candidate_registration") | |
| try: | |
| source = Path(weights_path) | |
| source_invalid = source.is_symlink() or not source.is_file() or source.stat().st_size == 0 | |
| except (OSError, ValueError, TypeError) as error: | |
| raise RegistryError("CHECKPOINT_NOT_FOUND", "candidate_checkpoint") from error | |
| if source_invalid: | |
| raise RegistryError("CHECKPOINT_NOT_FOUND", "candidate_checkpoint") | |
| destination = (self.challenger_dir if state == "challenger" else self.archive_dir) / (model_id + ".pt") | |
| with self._registration_lock(): | |
| data = self._read_data() | |
| if model_id in data["models"] or destination.exists() or destination.is_symlink(): | |
| raise RegistryError("MODEL_ID_ALREADY_EXISTS", "candidate_registration") | |
| digest = hashlib.sha256() | |
| try: | |
| # ID衝突・別WriterのCheckpointを上書きしない。 | |
| with source.open("rb") as incoming, destination.open("xb") as outgoing: | |
| for block in iter(lambda: incoming.read(1024 * 1024), b""): | |
| outgoing.write(block) | |
| digest.update(block) | |
| outgoing.flush() | |
| os.fsync(outgoing.fileno()) | |
| except FileExistsError as error: | |
| raise RegistryError("MODEL_ID_ALREADY_EXISTS", "candidate_registration") from error | |
| except OSError as error: | |
| # 新規の未登録Checkpointは調査・復旧用に残す。成功扱いしない。 | |
| raise RegistryError("CHECKPOINT_WRITE_FAILED", "candidate_checkpoint") from error | |
| record = { | |
| "model_id": model_id, "model_type": model_type, "state": state, | |
| "weights_path": str(destination), | |
| "checkpoint_sha256": digest.hexdigest(), | |
| "created_at": datetime.now(timezone.utc).isoformat(), | |
| "objective_metrics": metrics or {}, "config": config or {}, | |
| "regression_status": "PENDING_VERIFICATION", | |
| "validation_status": "NOT_RUN", "benchmark_status": "NOT_RUN", | |
| "promotion_status": "BLOCKED_RECOVERY_GATE", "notes": notes | |
| } | |
| data["models"][model_id] = record | |
| self._write_data(data) | |
| return record | |
| def get_champion(self, model_type: str = "refiner") -> Optional[Dict[str, Any]]: | |
| """Returns metadata of currently active Champion model.""" | |
| data = self._read_data() | |
| champ_id = data.get("active_champion", {}).get(model_type) | |
| if champ_id and champ_id in data.get("models", {}): | |
| return data["models"][champ_id] | |
| return None | |
| def get_challengers(self, model_type: str = "refiner") -> List[Dict[str, Any]]: | |
| """Lists all Challenger candidate models waiting for review.""" | |
| data = self._read_data() | |
| res = [] | |
| for m in data.get("models", {}).values(): | |
| if m.get("model_type") == model_type and m.get("state") == "challenger": | |
| res.append(m) | |
| return res | |
| def promote_to_champion(self, model_id: str) -> bool: | |
| # Current P0: 実Validation・Benchmark・権限の契約が未接続のため閉じる。 | |
| raise RegistryError("RECOVERY_GATE_REQUIRED", "promotion_gate") | |
| def rollback_to_previous_champion(self, model_type: str = "refiner") -> bool: | |
| """Rolls back to the most recently archived Champion model.""" | |
| if self.read_only: | |
| raise RegistryError("MODEL_REGISTRY_UNAVAILABLE", "read_only_status") | |
| data = self._read_data() | |
| archived = [ | |
| m for m in data.get("models", {}).values() | |
| if m.get("model_type") == model_type and m.get("state") == "archived" | |
| ] | |
| if not archived: | |
| print(f"[ModelRegistry] No archived champion found to rollback for {model_type}.") | |
| return False | |
| # Sort by creation / promotion timestamp descending | |
| archived.sort(key=lambda x: x.get("created_at", ""), reverse=True) | |
| target = archived[0] | |
| return self.promote_to_champion(target["model_id"]) | |
| def generate_comparison_report(self, champion_id: str, challenger_id: str) -> Dict[str, Any]: | |
| data = self._read_data() | |
| champion = data["models"].get(champion_id) | |
| candidate = data["models"].get(challenger_id) | |
| if champion is None or candidate is None: | |
| raise RegistryError("MODEL_ID_INVALID", "model_comparison") | |
| # 別々の評価値を同じ条件の比較と推定しない。由来・同一区間の比較契約は未接続。 | |
| return { | |
| "previous_champion": champion_id, "candidate": challenger_id, | |
| "metrics_comparison": { | |
| "overall_loss_delta": None, "si_sdr_delta_db": None, | |
| "leakage_reduction_pct": None | |
| }, | |
| "regression_status": "UNVERIFIED", | |
| "comparison_status": "UNKNOWN" | |
| } | |