|
| 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 asyncio import CancelledError |
| 10 | +from dataclasses import dataclass |
| 11 | +from pathlib import Path |
| 12 | +from typing import Generic, TypeVar, cast |
| 13 | + |
| 14 | +from frequenz.channels.file_watcher import EventType, FileWatcher |
| 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 ModelManager(BackgroundService, Generic[T]): |
| 32 | + """Load, update, monitor and retrieve machine learning models.""" |
| 33 | + |
| 34 | + def __init__(self, model_paths: dict[str, Path]): |
| 35 | + """Initialize the model manager with the specified model paths. |
| 36 | +
|
| 37 | + Args: |
| 38 | + model_paths: A dictionary of model keys and their corresponding file paths. |
| 39 | + """ |
| 40 | + super().__init__() |
| 41 | + self._models: dict[str, _Model[T]] = {} |
| 42 | + self.model_paths = model_paths |
| 43 | + self.load_models() |
| 44 | + |
| 45 | + def load_models(self) -> None: |
| 46 | + """Load the models from the specified paths.""" |
| 47 | + for key, path in self.model_paths.items(): |
| 48 | + self._models[key] = _Model(data=self._load(path), path=path) |
| 49 | + |
| 50 | + def _load(self, path: Path) -> T: |
| 51 | + """Load the model from the specified path. |
| 52 | +
|
| 53 | + Args: |
| 54 | + path: The path to the model file. |
| 55 | +
|
| 56 | + Returns: |
| 57 | + T: The loaded model data. |
| 58 | +
|
| 59 | + Raises: |
| 60 | + FileNotFoundError: If the model file does not exist. |
| 61 | + """ |
| 62 | + if not path.exists(): |
| 63 | + raise FileNotFoundError(f"The model path {path} does not exist.") |
| 64 | + with path.open("rb") as file: |
| 65 | + return cast(T, pickle.load(file)) |
| 66 | + |
| 67 | + def start(self) -> None: |
| 68 | + """Start the model monitoring service by creating a background task.""" |
| 69 | + if not self.is_running: |
| 70 | + task = asyncio.create_task(self.run()) |
| 71 | + self._tasks.add(task) |
| 72 | + _logger.info("Started ModelManager service with task %s", task) |
| 73 | + |
| 74 | + async def run(self) -> None: |
| 75 | + """Monitor model file paths and reload models as necessary.""" |
| 76 | + model_paths = [model.path for model in self._models.values()] |
| 77 | + file_watcher = FileWatcher(paths=list(model_paths)) |
| 78 | + _logger.info("Monitoring model paths for changes.") |
| 79 | + async for event in file_watcher: |
| 80 | + if event.type in (EventType.CREATE, EventType.MODIFY): |
| 81 | + _logger.info("Model file %s modified, reloading...", event.path) |
| 82 | + self.reload_model(Path(event.path)) |
| 83 | + |
| 84 | + def reload_model(self, path: Path) -> None: |
| 85 | + """Reload the model from the specified path. |
| 86 | +
|
| 87 | + Args: |
| 88 | + path: The path to the model file. |
| 89 | + """ |
| 90 | + for key, model in self._models.items(): |
| 91 | + if model.path == path: |
| 92 | + try: |
| 93 | + model.data = self._load(path) |
| 94 | + _logger.info("Successfully reloaded model from %s", path) |
| 95 | + except Exception as e: # pylint: disable=broad-except |
| 96 | + _logger.error("Failed to reload model from %s: %s", path, e) |
| 97 | + |
| 98 | + async def stop(self, msg: str | None = None) -> None: |
| 99 | + """Stop all model monitoring tasks with enhanced exception handling. |
| 100 | +
|
| 101 | + Args: |
| 102 | + msg: An optional message to log when stopping the service. |
| 103 | + """ |
| 104 | + _logger.info("Stopping ModelManager service: %s", msg) |
| 105 | + # Attempt to cancel all running tasks |
| 106 | + for task in list(self._tasks): |
| 107 | + task.cancel() |
| 108 | + try: |
| 109 | + await task # Wait for task to be cancelled |
| 110 | + except CancelledError: |
| 111 | + _logger.info("Task %s cancelled successfully", task) |
| 112 | + except Exception as e: # pylint: disable=broad-except |
| 113 | + _logger.error("Error while cancelling task %s: %s", task, e) |
| 114 | + |
| 115 | + # Call the parent stop method if it handles additional teardown |
| 116 | + try: |
| 117 | + await super().stop(msg) |
| 118 | + except Exception as e: # pylint: disable=broad-except |
| 119 | + _logger.error("Error during stop in superclass: %s", e) |
| 120 | + |
| 121 | + def get_model(self, key: str) -> T: |
| 122 | + """Retrieve a loaded model by key. |
| 123 | +
|
| 124 | + Args: |
| 125 | + key: The key of the model to retrieve. |
| 126 | +
|
| 127 | + Returns: |
| 128 | + The loaded model data. |
| 129 | +
|
| 130 | + Raises: |
| 131 | + KeyError: If the model with the specified key is not found. |
| 132 | + """ |
| 133 | + try: |
| 134 | + return self._models[key].data |
| 135 | + except KeyError as exc: |
| 136 | + raise KeyError(f"Model with key '{key}' is not found.") from exc |
0 commit comments