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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
"""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: <ConfigClass> | 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",
]