|
| 1 | +# License: MIT |
| 2 | +# Copyright © 2024 Frequenz Energy-as-a-Service GmbH |
| 3 | + |
| 4 | +"""Load, update, monitor and retrieve machine learning models.""" |
| 5 | + |
| 6 | +import asyncio |
| 7 | +import logging |
| 8 | +import pickle |
| 9 | +from dataclasses import dataclass |
| 10 | +from pathlib import Path |
| 11 | +from typing import Generic, TypeVar, cast |
| 12 | + |
| 13 | +from frequenz.channels.file_watcher import EventType, FileWatcher |
| 14 | +from typing_extensions import override |
| 15 | + |
| 16 | +from frequenz.sdk.actor import BackgroundService |
| 17 | + |
| 18 | +_logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | +T = TypeVar("T") |
| 21 | + |
| 22 | + |
| 23 | +@dataclass |
| 24 | +class _Model(Generic[T]): |
| 25 | + """Represent a machine learning model.""" |
| 26 | + |
| 27 | + data: T |
| 28 | + path: Path |
| 29 | + |
| 30 | + |
| 31 | +class ModelNotFoundError(Exception): |
| 32 | + """Exception raised when a model is not found.""" |
| 33 | + |
| 34 | + def __init__(self, key: str) -> None: |
| 35 | + """Initialize the exception with the specified model key. |
| 36 | +
|
| 37 | + Args: |
| 38 | + key: The key of the model that was not found. |
| 39 | + """ |
| 40 | + super().__init__(f"Model with key '{key}' is not found.") |
| 41 | + |
| 42 | + |
| 43 | +class ModelManager(BackgroundService, Generic[T]): |
| 44 | + """Load, update, monitor and retrieve machine learning models.""" |
| 45 | + |
| 46 | + def __init__(self, model_paths: dict[str, Path], *, name: str | None = None): |
| 47 | + """Initialize the model manager with the specified model paths. |
| 48 | +
|
| 49 | + Args: |
| 50 | + model_paths: A dictionary of model keys and their corresponding file paths. |
| 51 | + name: The name of the model manager service. |
| 52 | + """ |
| 53 | + super().__init__(name=name) |
| 54 | + self._models: dict[str, _Model[T]] = {} |
| 55 | + self.model_paths = model_paths |
| 56 | + self.load_models() |
| 57 | + |
| 58 | + def load_models(self) -> None: |
| 59 | + """Load the models from the specified paths.""" |
| 60 | + for key, path in self.model_paths.items(): |
| 61 | + self._models[key] = _Model(data=self._load(path), path=path) |
| 62 | + |
| 63 | + @staticmethod |
| 64 | + def _load(path: Path) -> T: |
| 65 | + """Load the model from the specified path. |
| 66 | +
|
| 67 | + Args: |
| 68 | + path: The path to the model file. |
| 69 | +
|
| 70 | + Returns: |
| 71 | + T: The loaded model data. |
| 72 | +
|
| 73 | + Raises: |
| 74 | + ModelNotFoundError: If the model file does not exist. |
| 75 | + """ |
| 76 | + try: |
| 77 | + with path.open("rb") as file: |
| 78 | + return cast(T, pickle.load(file)) |
| 79 | + except FileNotFoundError as exc: |
| 80 | + raise ModelNotFoundError(str(path)) from exc |
| 81 | + |
| 82 | + @override |
| 83 | + def start(self) -> None: |
| 84 | + """Start the model monitoring service by creating a background task.""" |
| 85 | + if not self.is_running: |
| 86 | + task = asyncio.create_task(self._monitor_paths()) |
| 87 | + self._tasks.add(task) |
| 88 | + _logger.info( |
| 89 | + "%s: Started ModelManager service with task %s", |
| 90 | + self.name, |
| 91 | + task, |
| 92 | + ) |
| 93 | + |
| 94 | + async def _monitor_paths(self) -> None: |
| 95 | + """Monitor model file paths and reload models as necessary.""" |
| 96 | + model_paths = [model.path for model in self._models.values()] |
| 97 | + file_watcher = FileWatcher( |
| 98 | + paths=list(model_paths), event_types=[EventType.CREATE, EventType.MODIFY] |
| 99 | + ) |
| 100 | + _logger.info("%s: Monitoring model paths for changes.", self.name) |
| 101 | + async for event in file_watcher: |
| 102 | + _logger.info( |
| 103 | + "%s: Reloading model from file %s due to a %s event...", |
| 104 | + self.name, |
| 105 | + event.path, |
| 106 | + event.type.name, |
| 107 | + ) |
| 108 | + self.reload_model(Path(event.path)) |
| 109 | + |
| 110 | + def reload_model(self, path: Path) -> None: |
| 111 | + """Reload the model from the specified path. |
| 112 | +
|
| 113 | + Args: |
| 114 | + path: The path to the model file. |
| 115 | + """ |
| 116 | + for key, model in self._models.items(): |
| 117 | + if model.path == path: |
| 118 | + try: |
| 119 | + model.data = self._load(path) |
| 120 | + _logger.info( |
| 121 | + "%s: Successfully reloaded model from %s", |
| 122 | + self.name, |
| 123 | + path, |
| 124 | + ) |
| 125 | + except Exception: # pylint: disable=broad-except |
| 126 | + _logger.exception("Failed to reload model from %s", path) |
| 127 | + |
| 128 | + def get_model(self, key: str) -> T: |
| 129 | + """Retrieve a loaded model by key. |
| 130 | +
|
| 131 | + Args: |
| 132 | + key: The key of the model to retrieve. |
| 133 | +
|
| 134 | + Returns: |
| 135 | + The loaded model data. |
| 136 | +
|
| 137 | + Raises: |
| 138 | + KeyError: If the model with the specified key is not found. |
| 139 | + """ |
| 140 | + try: |
| 141 | + return self._models[key].data |
| 142 | + except KeyError as exc: |
| 143 | + raise KeyError(f"Model with key '{key}' is not found.") from exc |
0 commit comments