File size: 5,079 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
"""In-process ChatTime engine for `llm_ts` family.

The authors' `ChatTime` class (`baselines/_vendor/chattime/model/model.py`)
runs as a Hugging Face `pipeline("text-generation", ...)` over `LlamaForCausalLM`
and applies a custom 10K-bin numeric tokenisation (`utils.tools.Discretizer`,
`Serializer`) plus their own prompt template (`utils.prompt.getPrompt`).
That pipeline is fundamentally not an OpenAI-compatible chat API and cannot
be served via `vllm serve`; the runner must load it in-process and inject it
as the method's ``engine`` so `methods/llm_ts_reason.py:ChatTime._call_t1_batch`
takes the numeric path (`engine.predict(history)`).

This wrapper:
1. Adds the vendor dir to ``sys.path`` (vendor uses ``from utils.prompt ...``
   imports relative to its own root).
2. Instantiates the vendor `ChatTime(model_path=...)` once.
3. Exposes a `.predict(history, pred_len=...)` API compatible with the
   methods-side `engine.predict(hist)` call site.

Memory note: per ``feedback_use_official_code``, this uses the vendored
authors' code unmodified rather than reimplementing the discretizer or
prompt protocol from the paper text.
"""

from __future__ import annotations

import sys
from pathlib import Path
from typing import Any

import numpy as np


_VENDOR_ROOT = (
    Path(__file__).resolve().parent.parent
    / "baselines" / "_vendor" / "chattime"
)


def _load_vendor_chattime_class():
    """Import ``baselines/_vendor/chattime/model/model.py:ChatTime``."""
    vendor_str = str(_VENDOR_ROOT)
    if vendor_str not in sys.path:
        sys.path.insert(0, vendor_str)
    # The vendor `model/model.py` does `from utils.prompt import getPrompt`,
    # which only resolves when the vendor root is on sys.path.
    from model.model import ChatTime as _VendorChatTime  # type: ignore
    return _VendorChatTime


class ChatTimeEngine:
    """Engine adapter for the vendored ChatTime author code.

    Construct once per run (model load is expensive). The vendor
    `ChatTime(...)` constructor requires ``hist_len`` and ``pred_len``
    up-front; we pass dummy values at construction and override them per
    `predict()` call from the actual lookback / horizon implied by the
    history array and an explicit ``pred_len`` kwarg.
    """

    def __init__(
        self,
        model_path: str = "ChengsenWang/ChatTime-1-7B-Chat",
        *,
        max_pred_len: int = 16,
        num_samples: int = 8,
    ) -> None:
        VendorChatTime = _load_vendor_chattime_class()
        # The vendor class hard-requires non-None hist_len/pred_len at init
        # only for the validation guard in `predict`; the constructor itself
        # accepts any positive ints. Provide dummies; predict() overrides.
        self._impl = VendorChatTime(
            model_path=model_path,
            hist_len=1,
            pred_len=1,
            max_pred_len=int(max_pred_len),
            num_samples=int(num_samples),
        )
        self.model_id = model_path

    def predict(
        self,
        history: np.ndarray,
        *,
        pred_len: int | None = None,
        context: Any = None,
    ) -> np.ndarray:
        """Forecast the next ``pred_len`` steps after ``history``.

        Parameters
        ----------
        history
            1-D ``np.ndarray`` of length ``lookback`` (close-price series).
        pred_len
            Forecast horizon. Defaults to 21 if not set (the
            ``methods/llm_ts_reason.py`` `_LLMTSBase` default for T1).
        context
            Optional natural-language context string (forwarded to the
            authors' ``getPrompt(flag='prediction', context=...)``).
        """
        hist_arr = np.asarray(history, dtype=np.float64).ravel()
        H = int(pred_len if pred_len is not None else 21)
        self._impl.hist_len = int(hist_arr.shape[0])
        self._impl.pred_len = H
        try:
            out = self._impl.predict(hist_arr, context=context)
        except Exception:
            # Authors' pipeline raised on this row (e.g. tokenization /
            # generation edge case). Per the "use upstream code unmodified"
            # discipline we don't retry-via-chat; emit an all-NaN row so the
            # methods-side parser records this cell as unparseable and the
            # eval fillna-then-mean rule handles it.
            return np.full((H,), np.nan, dtype=np.float32)
        arr = np.asarray(out, dtype=np.float32)
        if arr.shape[0] < H:
            arr = np.concatenate([arr, np.full(H - arr.shape[0], np.nan, dtype=np.float32)])
        return arr[:H]

    # Stub for the methods-side chat-completion fallback path. The fallback
    # is irrelevant for ChatTime (we always have the numeric predict path);
    # returning an empty string makes `_parse_horizon_list` yield None, which
    # the runner converts to a NaN row consistent with `predict`'s contract.
    def chat_complete(self, *args, **kwargs) -> str:  # noqa: D401, ARG002
        return ""

    def chat_complete_batch(self, prompts: list[str], **kwargs):  # noqa: ARG002
        return ["" for _ in prompts]