"""Zero-shot time-series foundation-model (TSFM) methods (T1 only). Three classes, all ``family="tsfm"``, ``tasks=frozenset({"T1"})``: - :class:`Chronos2` -- Amazon ``amazon/chronos-2`` decoder-only TSFM. - :class:`Moirai2` -- Salesforce ``Salesforce/moirai-2.0-R-small`` universal TS transformer with distribution heads. - :class:`TimesFM` -- Google ``google/timesfm-1.0-200m-pytorch`` patch decoder, ~200M params. Contract (sklearn-style, per the unified-API plan):: M(*, task: str = "T1", config: | None = None) M.fit(X, y, *, seed: int = 42) # ZS: no parameter learning; # records the close-feature # index from X shape M.predict(X) -> np.ndarray # (N, horizon) close trajectory M.save(path) / M.load(path) # HF save_pretrained + manifest Hard rules (also enforced in ``tests/test_layer_isolation.py``): * No benchmark IO. Loading HF model weights from the HF cache is fine; reading benchmark parquets is NOT. * No eval imports. * No ``meta`` consumption -- methods take only ``X`` (and at fit time, ``y``). * No subsampling, canonical-index joins, or dataframe joins inside ``predict``. Model-specific monkey-patches (preserved verbatim from the legacy ``baselines/tsfm.py`` runners; documented in ``methods/_vendored/CHANGES.md``): * **Moirai 2.0 gluonts-0.16 wrap**: uni2ts 2.0 was validated against an older gluonts where ``Moirai2Forecast.forward`` returned ``outputs`` directly. gluonts >=0.16's ``QuantileForecastGenerator.__call__`` instead unpacks ``(outputs,), loc, scale = make_predictions(...)`` and iterates the batch calling ``output.T``, expecting ``(B, future_time, num_quantiles)`` so ``.T`` yields ``(num_quantiles, future_time)``. ``Moirai2Forecast`` forward returns ``(B, num_quantiles, future_time)`` -- we transpose into ``(B, future_time, num_quantiles)`` and wrap into the 3-tuple. Idempotent via the ``_macrolens_gluonts016_wrap_applied`` sentinel. Sundial (THU) is NOT in the panel: its HF Hub modeling code requires transformers 4.40.x, which conflicts with the rest of MacroLens (transformers >=4.45 for vLLM 0.20 + Llama-4 / Gemma-4 / EXAONE FP8). Time-MoE was dropped from the panel in 2026-05 due to NaN propagation during long-horizon autoregressive prediction. Both are documented in ``methods/_vendored/CHANGES.md``. """ from __future__ import annotations import json import os import pathlib from typing import Any, ClassVar import numpy as np import pandas as pd from ._config import ( Chronos2Config, Moirai2Config, TimesFMConfig, TSFMConfig, ) from ._registry import register from .base import Method, _HFSaveMixin _T1_ONLY = frozenset({"T1"}) # ── Shared helpers ──────────────────────────────────────────────────────── def _resolve_device(device: str) -> str: """Map the ``"auto"`` literal onto cuda-or-cpu, preserving explicit values.""" if device == "auto": try: import torch return "cuda" if torch.cuda.is_available() else "cpu" except ImportError: return "cpu" return device def _coerce_t1_input(X: Any) -> np.ndarray: """Validate / coerce a T1 X argument to a contiguous ``(N, L, F)`` float32 ndarray.""" arr = np.asarray(X, dtype=np.float32) if arr.ndim != 3: raise ValueError( f"T1 TSFM predict expects X shape (N, lookback, F); got {arr.shape}" ) return arr def _close_panel(X: np.ndarray, target_idx: int) -> np.ndarray: """Slice the close column from a ``(N, L, F)`` panel.""" if target_idx < 0 or target_idx >= X.shape[2]: raise ValueError( f"target_idx={target_idx} out of bounds for X with F={X.shape[2]}" ) return X[:, :, int(target_idx)] def _check_horizon(value: int | None) -> int: if value is None or int(value) <= 0: raise RuntimeError( "TSFM .predict requires a positive horizon, captured at .fit time " "from y.shape[-1]; got horizon = " f"{value}. Call fit(X_train, y_train) first." ) return int(value) def _maybe_set_deterministic() -> None: """Honour ``MACROLENS_DETERMINISTIC=1`` like the rest of the unified API.""" if os.environ.get("MACROLENS_DETERMINISTIC", "0") != "1": return try: import torch torch.use_deterministic_algorithms(True) torch.backends.cudnn.deterministic = True # type: ignore[attr-defined] except (ImportError, RuntimeError): pass # ── Moirai 2.0 idempotent monkey-patch ──────────────────────────────────── def _apply_moirai2_gluonts016_wrap() -> None: """Bridge the uni2ts-2.0 / gluonts-0.16 forward protocol gap. Re-applies are no-ops thanks to the sentinel ``Moirai2Forecast._macrolens_gluonts016_wrap_applied``. """ from uni2ts.model.moirai2 import Moirai2Forecast if getattr(Moirai2Forecast, "_macrolens_gluonts016_wrap_applied", False): return _orig_fwd = Moirai2Forecast.forward def _wrapped_fwd(self, *args, **kwargs): # type: ignore[no-redef] preds = _orig_fwd(self, *args, **kwargs) return (preds.transpose(1, 2),), None, None Moirai2Forecast.forward = _wrapped_fwd Moirai2Forecast._macrolens_gluonts016_wrap_applied = True # ── Common base for the ZS TSFM classes ────────────────────────────────── class _TSFMBase(_HFSaveMixin, Method): """Mixin scaffolding shared by the three T1-only ZS TSFM classes. Subclasses must: * inherit and call this base ``__init__``, * implement ``_load()`` (to construct the model), * implement ``_predict_close(close, horizon)`` returning an ``(N, H)`` float32 ndarray. """ family: ClassVar[str] = "tsfm" tasks: ClassVar[frozenset[str]] = _T1_ONLY # ``_config_class`` is populated by the ``@register`` decorator on every # concrete subclass; declare it here so static type-checkers + the # ``default_config`` classmethod below resolve cleanly. _config_class: ClassVar[type[TSFMConfig]] = TSFMConfig @classmethod def default_config(cls) -> TSFMConfig: return cls._config_class() def __init__( self, *, task: str = "T1", config: TSFMConfig | None = None, **kwargs: Any, ): if task not in self.tasks: raise ValueError( f"{self.__class__.__name__}: unsupported task {task!r} " f"(supports {sorted(self.tasks)})" ) self.task = task if config is None: config = self.default_config() if kwargs: config = type(config)(**{**config.model_dump(), **kwargs}) elif kwargs: raise TypeError( f"{self.__class__.__name__}: pass either `config=` or kwargs, not both" ) self.config = config self.target_idx: int = int(getattr(config, "target_idx", 0)) self.device: str = _resolve_device(self.config.device) self._model: Any = None self._loaded: bool = False self._horizon: int | None = None # ── Subclass hooks ── def _load(self) -> None: raise NotImplementedError def _predict_close(self, close: np.ndarray, *, horizon: int) -> np.ndarray: raise NotImplementedError # ── Method API ── def fit(self, X: Any, y: Any, *, seed: int = 42) -> "Method": # noqa: ARG002 """Zero-shot fit: capture horizon from ``y`` and validate ``X`` shape. No parameters are learned. Subclasses override only if they need a context-window setup at this point (none of the four do). """ _maybe_set_deterministic() Xa = _coerce_t1_input(X) ya = np.asarray(y, dtype=np.float32) if ya.ndim != 2 or ya.shape[0] != Xa.shape[0]: raise ValueError( f"T1 TSFM fit expects y shape (N, horizon) matching X (N, L, F); " f"got X={Xa.shape}, y={ya.shape}" ) self._horizon = int(ya.shape[1]) return self def predict(self, X: Any) -> np.ndarray: Xa = _coerce_t1_input(X) horizon = _check_horizon(self._horizon) if not self._loaded: self._load() self._loaded = True close = _close_panel(Xa, self.target_idx) out = self._predict_close(close, horizon=horizon) out = np.asarray(out, dtype=np.float32) if out.shape != (Xa.shape[0], horizon): raise RuntimeError( f"{self.__class__.__name__}._predict_close returned shape " f"{out.shape}; expected {(Xa.shape[0], horizon)}" ) return out # ── HF save / load hooks (overridable) ── def _hf_save(self, path: pathlib.Path) -> None: """Default writer: HF ``save_pretrained`` if available, else torch.save. Always writes ``ft_state.json`` recording the captured horizon and ``target_idx`` so ``load`` can reconstruct without rerunning ``fit``. """ path = pathlib.Path(path) ft_state = { "horizon": self._horizon, "target_idx": self.target_idx, "device": self.device, } (path / "ft_state.json").write_text(json.dumps(ft_state, indent=2)) model = self._model if model is None: return save_pretrained = getattr(model, "save_pretrained", None) if callable(save_pretrained): save_pretrained(str(path)) else: import torch torch.save( {"state": getattr(model, "state_dict", lambda: model)()}, path / "state.pt", ) def _hf_load(self, path: pathlib.Path) -> None: """Default loader: read ``ft_state.json`` then call ``self._load()``. Subclasses that want to read locally-saved weights instead of the HF hub override this; the four ZS classes don't fine-tune so the default (re-download from HF) is correct. """ path = pathlib.Path(path) state_path = path / "ft_state.json" if state_path.exists(): ft_state = json.loads(state_path.read_text()) self._horizon = ft_state.get("horizon") self.target_idx = int(ft_state.get("target_idx", self.target_idx)) # Re-load the underlying model (HF cache reuse keeps this cheap). self._load() self._loaded = True # ── Chronos-2 ───────────────────────────────────────────────────────────── @register( name="chronos2", family="tsfm", tasks={"T1"}, config_class=Chronos2Config, ) class Chronos2(_TSFMBase): """Amazon Chronos-2 zero-shot forecaster (``amazon/chronos-2``).""" config: Chronos2Config def __init__( self, *, task: str = "T1", config: Chronos2Config | None = None, **kwargs: Any, ): super().__init__(task=task, config=config, **kwargs) self._is_chronos2: bool = False def _load(self) -> None: # Auto-detect Chronos-1 (T5/Bolt) vs Chronos-2 via BaseChronosPipeline: # ChronosPipeline rejects Chronos-2's ``input_patch_size`` config field. import torch from chronos import BaseChronosPipeline, Chronos2Pipeline self._model = BaseChronosPipeline.from_pretrained( self.config.model_id, device_map=self.device, torch_dtype=torch.float32, ) self._is_chronos2 = isinstance(self._model, Chronos2Pipeline) def _predict_close(self, close: np.ndarray, *, horizon: int) -> np.ndarray: import torch n, _ = close.shape batch_size = int(self.config.batch_size) all_preds: list[np.ndarray] = [] contexts: list[Any] = [] def _flush(ctx_batch: list[Any]) -> np.ndarray: if self._is_chronos2: # Chronos-2: predict_quantiles returns (quantiles, mean) # where ``mean`` is a list of (n_variates, horizon) tensors. # Univariate => take the (1, horizon) mean per item. _, means = self._model.predict_quantiles( ctx_batch, prediction_length=horizon, quantile_levels=[0.5], ) preds = np.stack([ m.squeeze(0).cpu().numpy() if hasattr(m, "cpu") else np.asarray(m).squeeze(0) for m in means ]) else: # Chronos-1 (T5/Bolt): predict returns (B, num_samples, H). forecasts = self._model.predict( ctx_batch, prediction_length=horizon, num_samples=int(self.config.num_samples), ) preds = np.median(forecasts.numpy(), axis=1) return preds[:, :horizon].astype(np.float32) for i in range(n): contexts.append(torch.tensor(close[i], dtype=torch.float32)) if len(contexts) >= batch_size: all_preds.append(_flush(contexts)) contexts = [] if contexts: all_preds.append(_flush(contexts)) return np.concatenate(all_preds, axis=0) # ── Moirai 2.0 ──────────────────────────────────────────────────────────── @register( name="moirai2", family="tsfm", tasks={"T1"}, config_class=Moirai2Config, ) class Moirai2(_TSFMBase): """Salesforce Moirai 2.0 zero-shot forecaster (``Salesforce/moirai-2.0-R-small``).""" config: Moirai2Config def __init__( self, *, task: str = "T1", config: Moirai2Config | None = None, **kwargs: Any, ): super().__init__(task=task, config=config, **kwargs) # Apply the gluonts-0.16 wrap eagerly + idempotently so multiple # Moirai2 ctor calls do not re-wrap (sentinel guard inside). try: _apply_moirai2_gluonts016_wrap() except ImportError: # uni2ts may not be installed at construction time; the wrap is # re-applied lazily inside ``_load`` if needed. pass def _load(self) -> None: from uni2ts.model.moirai2 import Moirai2Module _apply_moirai2_gluonts016_wrap() self._model = Moirai2Module.from_pretrained(self.config.model_id) def _build_forecast_model(self, lookback: int, horizon: int) -> Any: from uni2ts.model.moirai2 import Moirai2Forecast return Moirai2Forecast( module=self._model, prediction_length=horizon, context_length=lookback, target_dim=1, feat_dynamic_real_dim=0, past_feat_dynamic_real_dim=0, ) def _predict_close(self, close: np.ndarray, *, horizon: int) -> np.ndarray: from gluonts.dataset.pandas import PandasDataset n, lookback = close.shape forecast_model = self._build_forecast_model(lookback, horizon) predictor = forecast_model.create_predictor(batch_size=1) preds = np.empty((n, horizon), dtype=np.float32) for i in range(n): ts_df = pd.DataFrame( {"target": close[i].astype(np.float32)}, index=pd.date_range("2024-01-01", periods=lookback, freq="B"), ) ds = PandasDataset({"target": ts_df}) forecasts = list(predictor.predict(ds)) if not forecasts: raise RuntimeError( f"Moirai predictor.predict returned no forecasts on " f"instance {i}; refusing to silently substitute persistence." ) median_pred = forecasts[0].median[:horizon] preds[i] = np.asarray(median_pred, dtype=np.float32) return preds # ── TimesFM ─────────────────────────────────────────────────────────────── @register( name="timesfm", family="tsfm", tasks={"T1"}, config_class=TimesFMConfig, ) class TimesFM(_TSFMBase): """Google TimesFM 1.0 zero-shot forecaster. Default checkpoint: ``google/timesfm-1.0-200m-pytorch``. """ config: TimesFMConfig def __init__( self, *, task: str = "T1", config: TimesFMConfig | None = None, granularity: str = "daily", **kwargs: Any, ): super().__init__(task=task, config=config, **kwargs) self._granularity = granularity self._loaded_horizon: int | None = None def _load(self) -> None: # No-op here: TimesFm requires `horizon_len` at construction time, so # the actual instantiation is deferred to ``_ensure_loaded(horizon)``. return def _ensure_loaded(self, horizon: int) -> None: import timesfm if self._model is not None and self._loaded_horizon == horizon: return self._model = timesfm.TimesFm( hparams=timesfm.TimesFmHparams( backend="gpu" if str(self.device).startswith("cuda") else "cpu", per_core_batch_size=int(self.config.per_core_batch_size), horizon_len=horizon, ), checkpoint=timesfm.TimesFmCheckpoint( huggingface_repo_id=self.config.model_id, ), ) self._loaded_horizon = horizon def _predict_close(self, close: np.ndarray, *, horizon: int) -> np.ndarray: self._ensure_loaded(horizon) freq_map = {"daily": 0, "weekly": 1, "monthly": 2} freq_code = freq_map.get(self._granularity, 0) n, _ = close.shape out: list[np.ndarray] = [] batch_size = int(self.config.batch_size) for start in range(0, n, batch_size): ctx = close[start : start + batch_size] forecasts, _ = self._model.forecast( [c.tolist() for c in ctx], freq=[freq_code] * len(ctx), ) arr = np.asarray(forecasts, dtype=np.float32)[:, :horizon] out.append(arr) return np.concatenate(out, axis=0) __all__ = [ "Chronos2", "Moirai2", "TimesFM", "_apply_moirai2_gluonts016_wrap", ]