File size: 8,490 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
"""Per-method typed Pydantic configurations for the MacroLens unified API.

Each method class declares its own ``MethodConfig`` subclass with typed,
validated, default-bearing hyperparameters. The runner records
``config.model_dump()`` into ``RunRecord.hyperparams`` for every result.
"""

from __future__ import annotations

from typing import Literal

import pydantic


class MethodConfig(pydantic.BaseModel):
    """Base for all method configs.

    ``model_config = ConfigDict(extra="forbid")`` so unknown kwargs raise at
    construction; methods can override to allow ``extra="allow"`` if they
    intentionally pass through to a wrapped library.
    """

    model_config = pydantic.ConfigDict(extra="forbid", frozen=True)


# ── Naive ──────────────────────────────────────────────────────────────────


class PersistenceConfig(MethodConfig):
    # Index of the "close" feature on the (N, lookback, F) X array. Since
    # X is a numpy ndarray (no column names), the runner must pass this
    # in via config; default 0 matches the convention that close is the
    # first numeric feature returned by the T1 loader.
    close_feature_idx: int = 0
    # Optional explicit horizon override; when None, fit() reads horizon
    # from y.shape[1] and stores it as self._horizon.
    horizon: int | None = None


class SectorMedianConfig(MethodConfig):
    fallback_to_global: bool = True


class MetroMedianConfig(MethodConfig):
    fallback_to_global: bool = True
    metro_key: Literal["city_state", "state", "state_property_type"] = (
        "state_property_type"
    )


class HistoricalAnalogueConfig(MethodConfig):
    fallback_to_global: bool = True


class LogSizeOLSConfig(MethodConfig):
    use_log_assets: bool = True
    sector_dummies: bool = True


# ── Classical ──────────────────────────────────────────────────────────────


class LightGBMConfig(MethodConfig):
    """LightGBM library defaults; only ``n_jobs`` is a system-level flag."""

    n_estimators: int = 100  # LightGBM default
    max_depth: int = -1  # LightGBM default (unlimited)
    learning_rate: float = 0.1  # LightGBM default
    subsample: float = 1.0  # LightGBM default
    colsample_bytree: float = 1.0  # LightGBM default
    n_jobs: int = 8  # system-level flag (not a hyperparameter)
    verbosity: int = -1
    t6_text_handling: Literal["sector_industry_only"] = "sector_industry_only"


class RandomForestConfig(MethodConfig):
    """sklearn RandomForestRegressor library defaults; ``n_jobs`` is system-level."""

    n_estimators: int = 100  # sklearn default
    max_depth: int | None = None  # sklearn default (unlimited)
    min_samples_leaf: int = 1  # sklearn default
    n_jobs: int = 8  # system-level flag (not a hyperparameter)
    t6_text_handling: Literal["sector_industry_only"] = "sector_industry_only"


# ── Sequence ───────────────────────────────────────────────────────────────


class SequenceConfig(MethodConfig):
    """Shared training-loop defaults aligned with each upstream paper's
    reference script (DLinear / iTransformer / ModernTCN — all 3 papers
    use train_epochs=10, batch_size=32, patience=3, no weight_decay)."""

    epochs: int = 10  # all three upstream papers use 10
    batch_size: int = 32  # all three upstream papers use 32
    learning_rate: float = 1e-4  # subclass overrides match each paper
    patience: int = 3  # all three upstream papers use 3
    weight_decay: float = 0.0  # upstream papers don't use weight_decay
    grad_clip: float = 1.0
    target_idx: int = 0


class DLinearConfig(SequenceConfig):
    """DLinear (Zeng et al. AAAI 2023; cure-lab/LTSF-Linear, ETTh1 ref)."""

    moving_avg: int = 25  # paper default
    learning_rate: float = 5e-3  # ETTh1 reference script lr=0.005


class ITransformerConfig(SequenceConfig):
    """iTransformer (Liu et al. ICLR 2024; thuml/iTransformer, ETTh1 ref)."""

    d_model: int = 128  # ETTh1 reference d_model=128
    n_heads: int = 8  # paper default
    e_layers: int = 2  # ETTh1 reference e_layers=2
    d_ff: int = 128  # ETTh1 reference d_ff=128
    dropout: float = 0.1  # paper default
    factor: int = 1  # paper default
    activation: str = "gelu"  # paper default
    learning_rate: float = 1e-4  # ETTh1 reference lr=0.0001


class ModernTCNConfig(SequenceConfig):
    """ModernTCN (Donghao & Xue ICLR 2024; luodhhh/ModernTCN, ETTh1 ref)."""

    patch_size: int = 16  # paper default
    patch_stride: int = 8  # paper default
    d_model: int = 64  # ETTh1 reference d_model=64
    kernel_size: int = 25  # paper default
    stem_ratio: int = 1  # paper default
    downsample_ratio: int = 2  # paper default
    ffn_ratio: int = 2  # paper default
    num_blocks: tuple[int, ...] = (1,)  # paper default
    large_size: tuple[int, ...] = (51,)  # paper default
    small_size: tuple[int, ...] = (5,)  # paper default
    dropout: float = 0.1  # paper default
    head_dropout: float = 0.1  # paper default
    revin: bool = True  # paper default
    affine: bool = True  # paper default
    learning_rate: float = 1e-3  # ETTh1 reference lr=0.001


# ── TSFM (zero-shot) ───────────────────────────────────────────────────────


class TSFMConfig(MethodConfig):
    """Shared base for Chronos2 / Moirai2 / TimesFM."""

    model_id: str = ""           # subclass overrides the default
    device: Literal["auto", "cpu", "cuda"] = "auto"
    batch_size: int = 32
    target_idx: int = 0          # close-column index in T1 X (N, L, F)


class Chronos2Config(TSFMConfig):
    model_id: str = "amazon/chronos-2"
    num_samples: int = 20


class Moirai2Config(TSFMConfig):
    model_id: str = "Salesforce/moirai-2.0-R-small"


class TimesFMConfig(TSFMConfig):
    model_id: str = "google/timesfm-1.0-200m-pytorch"
    per_core_batch_size: int = 32
    granularity: Literal["daily", "weekly", "monthly"] = "daily"


# ── LLM (frontier) ─────────────────────────────────────────────────────────


class LLMConfig(MethodConfig):
    model_id: str = ""
    tensor_parallel_size: int = 1
    max_model_len: int = 8192
    temperature: float = 0.0
    max_tokens: int = 256
    enable_thinking: bool = False
    # Number of in-context (X_train, y_train) examples to include in the
    # prompt at predict time. ``0`` (default) = pure zero-shot.
    in_context_k: int = 0
    # Smoke-test mode: ``predict`` returns deterministic fake outputs
    # without invoking the engine. Used when ``engine=None`` in CI.
    dry_run: bool = False


class LlamaScoutConfig(LLMConfig):
    model_id: str = "meta-llama/Llama-4-Scout-17B-16E-Instruct"
    tensor_parallel_size: int = 4


class Gemma4Config(LLMConfig):
    model_id: str = "google/gemma-4-31B-it"
    tensor_parallel_size: int = 2


class Qwen35Config(LLMConfig):
    model_id: str = "Qwen/Qwen3.5-27B-FP8"
    tensor_parallel_size: int = 1


# ── LLM-TS multi-task ──────────────────────────────────────────────────────


class LLMTSConfig(MethodConfig):
    model_id: str = ""
    device: Literal["auto", "cpu", "cuda"] = "auto"
    # Smoke-test mode: ``predict`` returns deterministic fake outputs without
    # invoking a real engine. Mirrors :class:`LLMConfig.dry_run`.
    dry_run: bool = False


class ChatTimeConfig(LLMTSConfig):
    model_id: str = "ChengsenWang/ChatTime-1-7B-Chat"
    hist_len: int = 63
    pred_len: int = 21


class TimeMQAConfig(LLMTSConfig):
    model_id: str = "Time-MQA/Qwen-2.5-7B"
    base_model_id: str = "Qwen/Qwen2.5-7B-Instruct"


# ── LLM fine-tune (deferred) ───────────────────────────────────────────────


class LLMFineTunedConfig(LLMConfig):
    lora_r: int = 16
    lora_alpha: int = 32
    epochs: int = 3
    learning_rate: float = 2e-4