Datasets:
File size: 9,918 Bytes
02412f8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | """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)"
)
|