"""Method base contract for the MacroLens unified API. Every method class implements this contract: class ConcreteMethod(Method): name = "..." family = "..." tasks = frozenset({...}) def __init__(self, *, task: str, config: MethodConfig | None = None, **kwargs): ... def fit(self, X, y, *, seed: int = 42) -> "Method": ... def predict(self, X) -> np.ndarray | pd.DataFrame: ... def save(self, path: pathlib.Path) -> None: ... @classmethod def load(cls, path: pathlib.Path) -> "Method": ... @classmethod def default_config(cls) -> MethodConfig: ... def hyperparams(self) -> dict[str, Any]: ... # actual config (post-init) def lib_versions(self) -> dict[str, str]: ... Hard rules (enforced by ``tests/test_layer_isolation.py`` and ``tests/test_method_contract.py``): * Methods do NOT call ``pd.read_parquet`` or any file IO. * Methods do NOT import the eval module. * Methods do NOT subsample, filter, or join with canonical indices. * Methods do NOT consume ``meta`` -- they take only ``X`` (and at fit time, ``y``). * ``predict`` return shape is task-determined per the ``method-task coverage matrix`` in the plan; the runner asserts shape. Per-family serialisation is handled by mixins (``_JoblibSaveMixin``, ``_TorchSaveMixin``, ``_HFSaveMixin``) defined in this module. Concrete methods inherit ONE of them. """ from __future__ import annotations import abc import importlib.metadata import json import pathlib from typing import TYPE_CHECKING, Any, ClassVar import numpy as np import pandas as pd if TYPE_CHECKING: from ._config import MethodConfig # ── Public Method ABC ────────────────────────────────────────────────────── class Method(abc.ABC): """Abstract base class for every MacroLens method. Subclasses MUST set the four class-level attributes below and implement :meth:`fit`, :meth:`predict`, :meth:`save`, :meth:`load`, and :meth:`default_config`. The :meth:`hyperparams` and :meth:`lib_versions` methods have sensible defaults inherited from the appropriate save-mixin. """ name: ClassVar[str] family: ClassVar[str] tasks: ClassVar[frozenset[str]] schema_version: ClassVar[int] = 1 # populated by __init__ in concrete subclasses task: str config: "MethodConfig" @abc.abstractmethod def fit(self, X: Any, y: Any, *, seed: int = 42) -> "Method": """Fit the method on (X, y). Returns self for chaining.""" @abc.abstractmethod def predict(self, X: Any) -> np.ndarray | pd.DataFrame: """Emit predictions for X. Shape determined by self.task.""" @abc.abstractmethod def save(self, path: pathlib.Path) -> None: """Persist fitted state to ``path`` (a directory). Writes ``manifest.json`` plus family-specific artefacts. """ @classmethod @abc.abstractmethod def load(cls, path: pathlib.Path) -> "Method": """Reconstruct a fitted method from ``path``. Raises if the manifest's ``schema_version`` is incompatible. """ @classmethod @abc.abstractmethod def default_config(cls) -> "MethodConfig": """Return the default ``MethodConfig`` for this class.""" # ── default helpers (override only if necessary) ── def hyperparams(self) -> dict[str, Any]: """Return the actual config used (post-init).""" return self.config.model_dump() def lib_versions(self) -> dict[str, str]: """Return a dict of {package: version} for libraries this method uses. Default returns the versions of numpy / pandas / scikit-learn / torch / transformers (whichever are installed). Subclasses may override to add or restrict. """ pkgs = ["numpy", "pandas", "scikit-learn", "torch", "transformers", "lightgbm", "vllm", "peft", "chronos-forecasting", "uni2ts", "timesfm"] out: dict[str, str] = {} for p in pkgs: try: out[p] = importlib.metadata.version(p) except importlib.metadata.PackageNotFoundError: pass return out # ── manifest helpers used by save/load ── def _manifest(self) -> dict[str, Any]: """Return the manifest dict written by ``save``.""" return { "name": self.name, "family": self.family, "tasks": sorted(self.tasks), "schema_version": self.schema_version, "task": self.task, "hyperparams": self.hyperparams(), "lib_versions": self.lib_versions(), } @staticmethod def _check_manifest(path: pathlib.Path, expected_name: str, expected_schema: int) -> dict[str, Any]: """Validate ``manifest.json`` at ``path`` and return its contents.""" m_path = pathlib.Path(path) / "manifest.json" if not m_path.exists(): raise FileNotFoundError(f"manifest.json missing at {m_path}") manifest = json.loads(m_path.read_text()) if manifest.get("name") != expected_name: raise ValueError( f"checkpoint name mismatch: expected {expected_name}, " f"found {manifest.get('name')}" ) if manifest.get("schema_version") != expected_schema: raise ValueError( f"schema_version mismatch: expected {expected_schema}, " f"found {manifest.get('schema_version')} -- run " f"tools/migrate_results.py if migrating from v{manifest.get('schema_version')}" ) return manifest # ── Per-family save/load mixins ─────────────────────────────────────────── class _JoblibSaveMixin: """Serialise via ``joblib.dump``/``joblib.load``. For naive + classical methods whose state is small (medians, regression coeffs, LightGBM Booster). """ def save(self: "Method", path: pathlib.Path) -> None: # type: ignore[misc] import joblib path = pathlib.Path(path) path.mkdir(parents=True, exist_ok=True) (path / "manifest.json").write_text(json.dumps(self._manifest(), indent=2)) joblib.dump(self.__dict__, path / "state.joblib") @classmethod def load(cls: type["Method"], path: pathlib.Path) -> "Method": # type: ignore[misc] import joblib path = pathlib.Path(path) manifest = Method._check_manifest(path, cls.name, cls.schema_version) state = joblib.load(path / "state.joblib") instance = cls.__new__(cls) instance.__dict__.update(state) return instance class _TorchSaveMixin: """Serialise PyTorch state_dict + config + scaler. For sequence methods (DLinear, ITransformer, ModernTCN). """ def save(self: "Method", path: pathlib.Path) -> None: # type: ignore[misc] import torch path = pathlib.Path(path) path.mkdir(parents=True, exist_ok=True) (path / "manifest.json").write_text(json.dumps(self._manifest(), indent=2)) # Subclasses set self._model (nn.Module), self._scaler, self._aux payload = { "state_dict": self._model.state_dict() if hasattr(self, "_model") else None, "config": self.config.model_dump(), "task": self.task, "aux": getattr(self, "_aux", {}), } torch.save(payload, path / "state.pt") if hasattr(self, "_scaler"): import joblib joblib.dump(self._scaler, path / "scaler.joblib") @classmethod def load(cls: type["Method"], path: pathlib.Path) -> "Method": # type: ignore[misc] import torch path = pathlib.Path(path) manifest = Method._check_manifest(path, cls.name, cls.schema_version) payload = torch.load(path / "state.pt", weights_only=False) instance = cls(task=payload["task"], config=cls.default_config().__class__(**payload["config"])) if payload["state_dict"] is not None and hasattr(instance, "_model"): instance._model.load_state_dict(payload["state_dict"]) if hasattr(instance, "_aux"): instance._aux = payload.get("aux", {}) scaler_path = path / "scaler.joblib" if scaler_path.exists(): import joblib instance._scaler = joblib.load(scaler_path) return instance class _HFSaveMixin: """Serialise via HuggingFace ``save_pretrained``/``from_pretrained``. For TSFM/LLM methods. Concrete classes override the ``_hf_save`` and ``_hf_load`` hooks for adapter handling (LoRA). """ def save(self: "Method", path: pathlib.Path) -> None: # type: ignore[misc] path = pathlib.Path(path) path.mkdir(parents=True, exist_ok=True) (path / "manifest.json").write_text(json.dumps(self._manifest(), indent=2)) self._hf_save(path) # subclass hook @classmethod def load(cls: type["Method"], path: pathlib.Path) -> "Method": # type: ignore[misc] path = pathlib.Path(path) manifest = Method._check_manifest(path, cls.name, cls.schema_version) instance = cls(task=manifest["task"], config=cls.default_config().__class__(**manifest["hyperparams"])) instance._hf_load(path) # subclass hook return instance def _hf_save(self, path: pathlib.Path) -> None: raise NotImplementedError( "subclass must implement _hf_save (write model + tokenizer + adapter)" ) def _hf_load(self, path: pathlib.Path) -> None: raise NotImplementedError( "subclass must implement _hf_load (read model + tokenizer + adapter)" )